package com.examination.client.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.examination.client.config.ConfigProperties;
import com.examination.client.config.ExcelWidthStyleStrategy;
import com.examination.client.domian.dto.*;
import com.examination.client.domian.vo.*;
import com.examination.client.entity.CourierDeliveryImageInfo;
import com.examination.client.entity.CourierInfo;
import com.examination.client.entity.CourierSite;
import com.examination.client.entity.UserInfo;
import com.examination.client.enums.*;
import com.examination.client.exception.BusinessException;
import com.examination.client.mapper.CourierInfoMapper;
import com.examination.client.mapper.CourierSiteInfoMapper;
import com.examination.client.mapper.CourierSiteMapper;
import com.examination.client.service.ICourierDeliveryImageService;
import com.examination.client.service.ICourierInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.examination.client.service.ICourierSiteService;
import com.examination.client.service.IUserInfoService;
import com.examination.client.util.*;
import com.google.common.collect.Lists;
import com.jfinal.template.stat.ast.If;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.http.util.TextUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 快递信息入库表 服务实现类
 * </p>
 *
 * @author xiaodong
 * @since 2021-10-17
 */
@Slf4j
@Service
public class CourierInfoServiceImpl extends ServiceImpl<CourierInfoMapper, CourierInfo> implements ICourierInfoService {

    @Resource
    CourierSiteMapper courierSiteMapper;

    @Resource
    CourierInfoMapper courierInfoMapper;

    @Resource
    CourierSiteInfoMapper courierSiteInfoMapper;
    @Resource
    ConfigProperties configProperties;
    @Resource
    ICourierSiteService courierSiteService;
    @Resource
    IUserInfoService userInfoService;

    @Resource
    ICourierDeliveryImageService courierDeliveryImageService;
    @Resource
    ICourierInfoService courierInfoService;

    @Override
    @Transactional
    public CourierInfo save(CourierInfoDTO courierInfoDTO) throws Exception {
        //log.info("扫码入库入参:{}", JsonUtils.toJson(courierInfoDTO));
        LambdaQueryWrapper<CourierInfo> query = new LambdaQueryWrapper<>();
        query.eq(CourierInfo::getCourierCode, courierInfoDTO.getCourierCode());
        query.eq(CourierInfo::getSiteId, UserInfoUtil.getSiteId());
        query.eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
        CourierInfo courierInfo = getOne(query);
        if (Objects.nonNull(courierInfo)) {
            //log.info("入库校验查询参数:code:{},siteId:{}", courierInfoDTO.getCourierCode(), UserInfoUtil.getSiteId());
            throw new RuntimeException("该快件已经入库");
        }


        Date date = new Date();
        courierInfo = new CourierInfo();
        CourierSite site = courierSiteService.getById(UserInfoUtil.getSiteId());

        //计算地址匹配度
        if (site.getParentId() == 0) {
            if (StringUtils.isBlank(courierInfoDTO.getCourierCode())) {
                throw new BusinessException("code is not null");
            }
//            if (courierInfoDTO.getCourierCode().length()<13) {
//                throw new BusinessException("code error");
//            }
            if (Objects.isNull(courierInfoDTO.getNextSiteId())) {
                throw new BusinessException("NextSiteId not null");
            }
            if (2 == courierInfoDTO.getType()) {
                if (courierInfoDTO.getUserPhone().length() != 11) {
                    throw new BusinessException("phone error");
                }
            }

            BeanUtils.copyProperties(courierInfoDTO, courierInfo);
            if (Objects.isNull(courierInfoDTO.getNextSiteId())) {
                LambdaQueryWrapper<CourierSite> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(CourierSite::getParentId, UserInfoUtil.getSiteId());
                List<CourierSite> courierSiteList = courierSiteMapper.selectList(queryWrapper);
                List<SuitabilityDTO> suitabilityList = Lists.newArrayList();
                if (!CollectionUtils.isEmpty(courierSiteList)) {
                    for (CourierSite courierSite : courierSiteList) {
                        if (StringUtils.isNotBlank(courierSite.getKeyword())) {
                            List<Float> suitabilitys = Lists.newArrayList();
                            String[] keywords = courierSite.getKeyword().split(",");
                            List<String> keywordList = Arrays.asList(keywords);
                            keywordList.forEach(e -> {
                                float suitability = SimilarityUtils.levenshtein(courierInfoDTO.getUserAddress(), e);
                                suitabilitys.add(suitability);
                            });
                            List<Float> scoreList = suitabilitys.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
                            if (CollectionUtil.isNotEmpty(suitabilitys)) {
                                SuitabilityDTO suitabilityDTO = new SuitabilityDTO();
                                suitabilityDTO.setNextSiteId(courierSite.getId());
                                suitabilityDTO.setSuitability(scoreList.get(0));
                                suitabilityList.add(suitabilityDTO);
                            }
                        }
                    }
                    List<SuitabilityDTO> suitabilityDTOList = suitabilityList.stream().sorted(Comparator.comparing(SuitabilityDTO::getSuitability).reversed()).collect(Collectors.toList());
                    courierInfo.setNextSiteId(suitabilityDTOList.get(0).getNextSiteId());
                }
            } else {
                courierInfo.setNextSiteId(courierInfoDTO.getNextSiteId());
            }
            courierInfo.setMainStorageImageUrl(courierInfoDTO.getMainStorageImageUrl());

        } else {
            if (!UserInfoUtil.getSiteId().equals(courierInfoDTO.getNextSiteId())) {
                throw new BusinessException("快件错分，请妥善保管");
            }
            LambdaQueryWrapper<CourierInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CourierInfo::getCourierCode, courierInfoDTO.getCourierCode());
            queryWrapper.eq(CourierInfo::getSiteId, site.getParentId());
            queryWrapper.eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
            CourierInfo courier = getOne(queryWrapper);
            if (Objects.isNull(courier)) {
                log.info("子账号入库检验是否在子账号存在: code:{},父siteId:{}", courierInfoDTO.getCourierCode(), site.getParentId());
                throw new BusinessException(BusinessExceptionEnum.ALREADY_STORAGE.code, BusinessExceptionEnum.ALREADY_STORAGE.msg);
            }

            courier.setUpdateTime(date);
            courier.setDeliveryTime(date);
            courier.setCourierStatus(CourierStatusEnum.DELIVERY.getCode());
            updateById(courier);

            BeanUtils.copyProperties(courier, courierInfo);
            courierInfo.setCourierStatus(CourierStatusEnum.STORAGE.getCode());
            courierInfo.setDeliveryTime(null);
            courierInfo.setNextSiteId(null);
            courierInfo.setSiteType(2);
            courierInfo.setStorageImageUrl(courierInfoDTO.getStorageImageUrl());
        }
        if (StringUtils.isNotBlank(courierInfoDTO.getUserPhone())) {
            courierInfo.setUserPhone(courierInfoDTO.getUserPhone());
            log.info("courierInfoDTO.getUserPhone()  --> " + courierInfoDTO.getUserPhone());
            if (courierInfoDTO.getUserPhone().contains("*")) {
                courierInfo.setUserPhoneHide(1);
            } else {
                courierInfo.setUserPhoneHide(0);
            }
        }
        courierInfo.setSiteId(UserInfoUtil.getSiteId());
        courierInfo.setStorageTime(date);
        courierInfo.setCreateTime(date);
        courierInfo.setUpdateTime(date);
        courierInfo.setOperatorId(UserInfoUtil.getUserid());
        save(courierInfo);
        if (StringUtils.isNotBlank(courierInfo.getUserPhone())) {
            if (site.getParentId() == 0) {
                if (Objects.nonNull(courierInfo.getNextSiteId())) {
                    CourierSite courierSite = courierSiteService.getById(courierInfo.getNextSiteId());
                    log.info("courierSite.getSiteName() 1 --> " + courierSite.getSiteName());
                    push(courierInfo.getUserPhone(), "1", courierInfo.getCourierName(), courierInfo.getCourierCode(), courierSite.getSiteName(), courierInfo.getUserAddress(), courierSite.getPhone());
                }

            } else {
                log.info("courierSite.getSiteName() 2 --> " + site.getSiteName());
                push(courierInfo.getUserPhone(), "2", courierInfo.getCourierName(), courierInfo.getCourierCode(), site.getSiteName(), site.getSiteAddress(), site.getPhone());
            }
        }
        return courierInfo;
    }

    @Override
    @Transactional
    public CourierInfo saveSubsite(CourierInfoDTO courierInfoDTO) throws Exception {
        log.info("扫码入库入参:{}", JsonUtils.toJson(courierInfoDTO));
        LambdaQueryWrapper<CourierInfo> query = new LambdaQueryWrapper<>();
        query.eq(CourierInfo::getCourierCode, courierInfoDTO.getCourierCode());
        query.eq(CourierInfo::getSiteId, UserInfoUtil.getSiteId());
        query.eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
        CourierInfo courierInfo = getOne(query);
        if (Objects.nonNull(courierInfo)) {
            log.info("入库校验查询参数:code:{},siteId:{}", courierInfoDTO.getCourierCode(), UserInfoUtil.getSiteId());
            throw new RuntimeException("该快件已经入库");
        }
        //主账号入库
        Date date = new Date();
        courierInfo = new CourierInfo();
        CourierSite site = courierSiteService.getById(UserInfoUtil.getSiteId());
        if (StringUtils.isBlank(courierInfoDTO.getCourierCode())) {
            throw new BusinessException("code is not null");
        }
        if (Objects.isNull(courierInfoDTO.getNextSiteId())) {
            throw new BusinessException("NextSiteId not null");
        }
        BeanUtils.copyProperties(courierInfoDTO, courierInfo);
        Integer nextSiteId = null;
        if (Objects.isNull(courierInfoDTO.getNextSiteId())) {
            LambdaQueryWrapper<CourierSite> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CourierSite::getParentId, UserInfoUtil.getSiteId());
            List<CourierSite> courierSiteList = courierSiteMapper.selectList(queryWrapper);
            List<SuitabilityDTO> suitabilityList = Lists.newArrayList();
            if (!CollectionUtils.isEmpty(courierSiteList)) {
                for (CourierSite courierSite : courierSiteList) {
                    if (StringUtils.isNotBlank(courierSite.getKeyword())) {
                        List<Float> suitabilitys = Lists.newArrayList();
                        String[] keywords = courierSite.getKeyword().split(",");
                        List<String> keywordList = Arrays.asList(keywords);
                        keywordList.forEach(e -> {
                            float suitability = SimilarityUtils.levenshtein(courierInfoDTO.getUserAddress(), e);
                            suitabilitys.add(suitability);
                        });
                        List<Float> scoreList = suitabilitys.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
                        if (CollectionUtil.isNotEmpty(suitabilitys)) {
                            SuitabilityDTO suitabilityDTO = new SuitabilityDTO();
                            suitabilityDTO.setNextSiteId(courierSite.getId());
                            suitabilityDTO.setSuitability(scoreList.get(0));
                            suitabilityList.add(suitabilityDTO);
                        }
                    }
                }
                List<SuitabilityDTO> suitabilityDTOList = suitabilityList.stream().sorted(Comparator.comparing(SuitabilityDTO::getSuitability).reversed()).collect(Collectors.toList());
                nextSiteId = suitabilityDTOList.get(0).getNextSiteId();
            }
        } else {
            nextSiteId = courierInfoDTO.getNextSiteId();
        }
        courierInfo.setNextSiteId(nextSiteId);
        courierInfo.setMainStorageImageUrl(courierInfoDTO.getMainStorageImageUrl());
        if (StringUtils.isNotBlank(courierInfoDTO.getUserPhone())) {
            courierInfo.setUserPhone(courierInfoDTO.getUserPhone());
            if (courierInfoDTO.getUserPhone().contains("*")) {
                courierInfo.setUserPhoneHide(1);
            } else {
                courierInfo.setUserPhoneHide(0);
            }
        }
        courierInfo.setSiteId(UserInfoUtil.getSiteId());
        courierInfo.setStorageTime(date);
        courierInfo.setCreateTime(date);
        courierInfo.setUpdateTime(date);
        courierInfo.setDeliveryTime(date);
        courierInfo.setOperatorId(UserInfoUtil.getUserid());
        courierInfo.setCourierStatus(CourierStatusEnum.DELIVERY.getCode());
        save(courierInfo);
        //子账号入库（主账号出库）
        courierInfo.setCourierStatus(CourierStatusEnum.STORAGE.getCode());
        courierInfo.setSiteId(nextSiteId);
        courierInfo.setDeliveryTime(null);
        courierInfo.setNextSiteId(null);
        courierInfo.setSiteType(2);
        courierInfo.setStorageImageUrl(courierInfoDTO.getStorageImageUrl());
        save(courierInfo);
//        if(StringUtils.isNotBlank(courierInfo.getUserPhone())) {
//            if (site.getParentId() == 0) {
//                if(Objects.nonNull(courierInfo.getNextSiteId())){
//                    CourierSite courierSite = courierSiteService.getById(courierInfo.getNextSiteId());
//                    log.info("courierSite.getSiteName() 1 --> " + courierSite.getSiteName());
//                    push(courierInfo.getUserPhone(), "1", courierInfo.getCourierName(), courierInfo.getCourierCode(), courierSite.getSiteName(), courierInfo.getUserAddress(), courierSite.getPhone());
//                }
//
//            } else {
//                log.info("courierSite.getSiteName() 2 --> " + site.getSiteName());
//                push(courierInfo.getUserPhone(), "2", courierInfo.getCourierName(), courierInfo.getCourierCode(), site.getSiteName(), site.getSiteAddress(), site.getPhone());
//            }
//        }
        return courierInfo;
    }

    @Override
    public Boolean modify(CourierInfoDTO courierInfoDTO) {
        log.info("快递编辑请求参数:{}", JsonUtils.toJson(courierInfoDTO));
        if (2 == courierInfoDTO.getType()) {
            if (courierInfoDTO.getUserPhone().length() != 11) {
                throw new RuntimeException("手机号有误请重新输入");
            }

        }
//        if (courierInfoDTO.getCourierCode().length()<13) {
//            throw new RuntimeException("单号格式错误");
//        }
        LambdaQueryWrapper<CourierInfo> query = new LambdaQueryWrapper<>();
        query.eq(CourierInfo::getCourierCode, courierInfoDTO.getCourierCode());
        query.eq(CourierInfo::getSiteId, UserInfoUtil.getSiteId());
        CourierInfo one = getOne(query);
        if (Objects.nonNull(one) && !one.getId().equals(courierInfoDTO.getId()) && !one.getCourierStatus().equals(4)) {
            throw new RuntimeException("该快递单号已经入库");
        }

        CourierInfo courierInfo = new CourierInfo();
        BeanUtils.copyProperties(courierInfoDTO, courierInfo);
        if (Objects.isNull(one.getNextSiteId())) {
            courierInfo.setNextSiteId(null);
        }
        courierInfo.setUpdateTime(new Date());
        return updateById(courierInfo);
    }

    @Override
    public Boolean modifyPhone(CourierInfoDTO courierInfoDTO) {
        log.info("修改手机号请求参数:{}", JsonUtils.toJson(courierInfoDTO));
        LambdaQueryWrapper<CourierInfo> query = new LambdaQueryWrapper<>();
        query.eq(CourierInfo::getId, courierInfoDTO.getId());
        CourierInfo one = getOne(query);
        CourierInfo courierInfo = new CourierInfo();
        BeanUtils.copyProperties(one, courierInfo);
        courierInfo.setUpdateTime(new Date());
        courierInfo.setUserPhone(courierInfoDTO.getUserPhone());
        if (!courierInfoDTO.getUserPhone().contains("*")) {
            courierInfo.setUserPhoneHide(0);
        } else {
            courierInfo.setUserPhoneHide(1);
        }
        return updateById(courierInfo);
    }

    @Override
    public TodayStatisticsVO statistics(TodayStatisticsQueryDTO todayStatisticsQueryDTO) {
        log.info("statistics  UserInfoUtil.getSiteId() --> " + UserInfoUtil.getSiteId());
        CourierSite courierSite = courierSiteService.getById(UserInfoUtil.getSiteId());

        TodayStatisticsVO todayStatisticsVO = new TodayStatisticsVO();
        String today = DateUtil.DateToString(new Date(), DateUtil.DATE_FORMAT_YYYY_MM_DD);

        LambdaQueryWrapper<CourierInfo> storageueryWrapper = new LambdaQueryWrapper<>();
        storageueryWrapper.eq(CourierInfo::getSiteId, UserInfoUtil.getSiteId())
                .like(CourierInfo::getStorageTime, today)
                .eq(CourierInfo::getCourierStatus, CourierStatusEnum.STORAGE.getCode());
        //今日入库数量
        int storageCount = count(storageueryWrapper);
        todayStatisticsVO.setStorageQuantity(storageCount);


        LambdaQueryWrapper<CourierInfo> deliveryQueryWrapper = new LambdaQueryWrapper<>();
        deliveryQueryWrapper.eq(CourierInfo::getSiteId, UserInfoUtil.getSiteId())
                .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode())
                .like(CourierInfo::getUpdateTime, today)
                .and(wrapper -> wrapper
                        .eq(CourierInfo::getCourierStatus, CourierStatusEnum.DELIVERY.getCode())
                        .or()
                        .eq(CourierInfo::getCourierStatus, CourierStatusEnum.HAVE_RECEIVED.getCode()));


        //今日出库数量
        int deliveryCount = count(deliveryQueryWrapper);
        todayStatisticsVO.setDeliveryQuantity(deliveryCount);


        if (courierSite.getParentId() != 0) {

            //今日待入库数量
            LambdaQueryWrapper<CourierInfo> shallStorageueryWrapper = new LambdaQueryWrapper<>();
            shallStorageueryWrapper.eq(CourierInfo::getNextSiteId, UserInfoUtil.getSiteId())
                    .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode())
                    .eq(CourierInfo::getCourierStatus, CourierStatusEnum.STORAGE.getCode());
            int shallStoragCount = count(shallStorageueryWrapper);
            todayStatisticsVO.setShallStorage(shallStoragCount);


            //退件出库记录
            LambdaQueryWrapper<CourierInfo> returnQuantityQueryWrapper = new LambdaQueryWrapper<>();
            returnQuantityQueryWrapper.eq(CourierInfo::getSiteId, UserInfoUtil.getSiteId())
                    .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode())
                    .eq(CourierInfo::getCourierStatus, CourierStatusEnum.RETURN_DELIVERY.getCode());
            int returnQuantity = count(returnQuantityQueryWrapper);
            todayStatisticsVO.setReturnQuantity(returnQuantity);


            //本月共入库
            String currentMonth = DateUtil.DateToString(new Date(), DateUtil.DATE_FORMAT_YYYY_MM);
            LambdaQueryWrapper<CourierInfo> monthStorageQuantityQueryWrapper = new LambdaQueryWrapper<>();
            monthStorageQuantityQueryWrapper.eq(CourierInfo::getSiteId, UserInfoUtil.getSiteId())
                    .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode())
                    .like(CourierInfo::getStorageTime, currentMonth);
            int monthStorageQuantity = count(monthStorageQuantityQueryWrapper);
            todayStatisticsVO.setMonthStorageQuantity(monthStorageQuantity);


            //库存待出库
            LambdaQueryWrapper<CourierInfo> stayDeliveryQuantityQueryWrapper = new LambdaQueryWrapper<>();
            stayDeliveryQuantityQueryWrapper.eq(CourierInfo::getSiteId, UserInfoUtil.getSiteId())
                    .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode())
                    .eq(CourierInfo::getCourierStatus, CourierStatusEnum.STORAGE.getCode());
            int stayDeliveryQuantity = count(stayDeliveryQuantityQueryWrapper);
            todayStatisticsVO.setStayDeliveryQuantity(stayDeliveryQuantity);
        } else {

            LambdaQueryWrapper<CourierInfo> returnQuantityQueryWrapper = new LambdaQueryWrapper<>();
            returnQuantityQueryWrapper
                    .eq(CourierInfo::getSiteId, UserInfoUtil.getSiteId())
                    .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode())
                    .and(wrapper -> wrapper
                                    .eq(CourierInfo::getCourierStatus, CourierStatusEnum.RETURN_STORAGE.getCode())
//                            .or()
//                            .eq(CourierInfo::getCourierStatus, CourierStatusEnum.RETURN_DELIVERY.getCode())
                    );


            int returnQuantity = count(returnQuantityQueryWrapper);
            todayStatisticsVO.setReturnQuantity(returnQuantity);


        }
        todayStatisticsVO.setPhone(configProperties.getPhone());

        return todayStatisticsVO;
    }

    @Override
    public CourierInfoDetailVO detail(String id) throws Exception {
        CourierInfo courierInfo = getById(id);

        CourierSite courierSite = courierSiteService.getById(courierInfo.getSiteId());

        //计算入库天数
        Date date = new Date();
        String today = DateUtil.DateToString(date, DateUtil.DATE_FORMAT_YYYY_MM_DD);
        String storageTime = DateUtil.DateToString(courierInfo.getStorageTime(), DateUtil.DATE_FORMAT_YYYY_MM_DD);
        long storageDays = DateUtil.getDaySub(storageTime, today);

        CourierInfoDetailVO courierInfoDetailDTO = new CourierInfoDetailVO();
        BeanUtils.copyProperties(courierInfo, courierInfoDetailDTO);
        courierInfoDetailDTO.setStorageDays(storageDays + 1);
        courierInfoDetailDTO.setSiteName(courierSite.getSiteName());

        //处理我的快递详情相关逻辑
        CourierSite childSite = new CourierSite();
        if (Objects.nonNull(courierInfo.getNextSiteId())) {
            childSite = courierSiteService.getById(courierInfo.getNextSiteId());
            courierInfoDetailDTO.setLoadTime(courierInfo.getCreateTime());
            courierInfoDetailDTO.setReturnCompletionTime(courierInfo.getDeliveryTime());
        } else {
            childSite = courierSite;
            LambdaQueryWrapper<CourierInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CourierInfo::getCourierCode, courierInfo.getCourierCode());
            queryWrapper.isNotNull(CourierInfo::getNextSiteId).last("limit 1");
            CourierInfo parentCourierInfo = getOne(queryWrapper);
            if (parentCourierInfo != null) {
                courierInfoDetailDTO.setLoadTime(parentCourierInfo.getCreateTime());
                courierInfoDetailDTO.setReturnCompletionTime(parentCourierInfo.getDeliveryTime());
            }
            courierInfoDetailDTO.setArrivalTime(courierInfo.getCreateTime());
            courierInfoDetailDTO.setTakeTime(courierInfo.getUpdateTime());
        }
        courierInfoDetailDTO.setChildSiteName(childSite.getSiteName());
        courierInfoDetailDTO.setChildSitePhone(childSite.getPhone());

        if (courierInfo.getNextSiteId() == null) {
            if (courierInfo.getCourierStatus().equals(CourierStatusEnum.STORAGE.getCode())) {
                courierInfoDetailDTO.setCourierDeliveryStatus(2);
            } else {
                courierInfoDetailDTO.setCourierDeliveryStatus(3);
            }
        } else {
            courierInfoDetailDTO.setCourierDeliveryStatus(1);
        }
        //短信状态
        courierInfoDetailDTO.setMessageAdviceStatus(courierInfo.getAdviceStatus());
        //主账号入库时间
        LambdaQueryWrapper<CourierInfo> query = new LambdaQueryWrapper<>();
        query.eq(CourierInfo::getNextSiteId, courierInfo.getSiteId())
                .eq(CourierInfo::getCourierCode, courierInfo.getCourierCode())
                .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
        CourierInfo mainCourierInfo = getOne(query);
        if (mainCourierInfo == null) {
            courierInfoDetailDTO.setMainStorageTime(courierInfo.getStorageTime());
        } else {
            courierInfoDetailDTO.setMainStorageTime(mainCourierInfo.getStorageTime());
        }
        //出库照片
        LambdaQueryWrapper<CourierDeliveryImageInfo> imageQueryWrapper = new LambdaQueryWrapper<>();
        imageQueryWrapper.eq(CourierDeliveryImageInfo::getCourierCode, courierInfo.getCourierCode());
        imageQueryWrapper.eq(CourierDeliveryImageInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
        CourierDeliveryImageInfo courierDeliveryImageInfo = courierDeliveryImageService.getOne(imageQueryWrapper);
        if (courierDeliveryImageInfo != null) {
            courierInfoDetailDTO.setImageUrl(courierDeliveryImageInfo.getImageUrl());
        }
        return courierInfoDetailDTO;
    }

    @Override
    public List<CourierSiteInfoDTO> siteCourierList1(TodayStatisticsQueryDTO todayStatisticsQueryDTO) {
        String appSite = UserInfoUtil.getAppSite();
        String[] ids = null;
        if (!TextUtils.isEmpty(appSite)) {
            if (appSite.contains(",")) {
                ids = appSite.split(",");
            } else {
                ids = new String[]{appSite};
            }
        }
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        String strDate = sdf1.format(new Date());
        System.out.println("ids ========= ");
        System.out.println(appSite);
        System.out.println(ids);
        List<CourierSiteInfoDTO> list = courierSiteInfoMapper.getCourierSiteInfo(appSite, strDate);
        return list;
    }

    @Override
    public List<TodaySiteStatisticsVO> siteCourierList(TodayStatisticsQueryDTO todayStatistics) {

        String appSite = UserInfoUtil.getAppSite();
        log.info("appSite --> {}", appSite);
        List<Integer> appSiteList = new ArrayList<>();
        if (!TextUtils.isEmpty(appSite)) {
            if (appSite.contains(",")) {
                String[] list = appSite.split(",");
                for (int i = 0; i < list.length; i++) {
                    appSiteList.add(Integer.parseInt(list[i]));
                }
            } else {
                appSiteList.add(Integer.parseInt(appSite));
            }
        }
        List<CourierSite> courierSiteList = new ArrayList<>();
        if (appSiteList != null && appSiteList.size() > 0) {
            LambdaQueryWrapper<CourierSite> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(CourierSite::getId, appSiteList);
            queryWrapper.eq(CourierSite::getParentId, UserInfoUtil.getSiteId());
            queryWrapper.eq(CourierSite::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
            queryWrapper.eq(CourierSite::getStatus, SiteStatusEnum.Enable.getCode());
            courierSiteList = courierSiteMapper.selectList(queryWrapper);
        }

        List<TodaySiteStatisticsVO> todaySiteStatisticsVOList = Lists.newArrayList();
        for (CourierSite courierSite : courierSiteList) {
            TodayStatisticsQueryDTO todayStatisticsQueryDTO = new TodayStatisticsQueryDTO();
            todayStatisticsQueryDTO.setChiefSiteId(courierSite.getId());
            TodayStatisticsVO todayStatisticsVO = siteStatistics(todayStatisticsQueryDTO);

            TodaySiteStatisticsVO todaySiteStatisticsVO = new TodaySiteStatisticsVO();
            todaySiteStatisticsVO.setSiteName(courierSite.getSiteName());
            todaySiteStatisticsVO.setSiteId(courierSite.getId());
            todaySiteStatisticsVO.setSubsiteIn(courierSite.getSubsiteIn());
            todaySiteStatisticsVO.setStorageQuantity(todayStatisticsVO.getStorageQuantity());
            todaySiteStatisticsVO.setDeliveryQuantity(todayStatisticsVO.getDeliveryQuantity());
            todaySiteStatisticsVO.setCourierCodeList(todayStatisticsVO.getCourierCodeList());
            todaySiteStatisticsVOList.add(todaySiteStatisticsVO);
        }
        return todaySiteStatisticsVOList;

    }

    /**
     * 今日待入库
     *
     * @return
     */
    @Override
    public TodaySiteStorageStatisticsVO todaySiteStorageStatistics() {
        Integer siteId = UserInfoUtil.getSiteId();
        Date date = new Date();
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = fmt.format(date);
        return courierSiteInfoMapper.getTodaySiteStorageStatistics(siteId, dateStr);
    }

    @Override
    @Transactional
    public Boolean batchSaveMain(DeliveryDTO deliveryDTO) {
        if (CollectionUtils.isEmpty(deliveryDTO.getCourierCodeList())) {
            throw new RuntimeException("参数不能为空");
        }
        System.out.println("UserInfoUtil.getSiteId()  ===== " + UserInfoUtil.getSiteId());
        //主账号批量入库
        if (BatchOperateEnum.STORAGE.getCode().equals(deliveryDTO.getType())) {
            //查询主账号已经入库的单号
            Integer nextSiteId = deliveryDTO.getNextSiteId();
            Integer subsiteIn = deliveryDTO.getSubsiteIn();
            Date date = new Date();
            List<String> courierCodeList = deliveryDTO.getCourierCodeList();
            System.out.println("courierCodeList ====== ");
            System.out.println(courierCodeList);
            LambdaQueryWrapper<CourierInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(CourierInfo::getCourierCode, courierCodeList);
            queryWrapper.eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
            List<CourierInfo> courierList = list(queryWrapper);
            //重复的删掉
            List<Integer> courierUpdateIdList = new ArrayList<>();
            for (CourierInfo courierInfo : courierList) {
                courierUpdateIdList.add(courierInfo.getId());
            }
            if (CollectionUtil.isNotEmpty(courierUpdateIdList)) {
                removeByIds(courierUpdateIdList);
            }
            //查询子账号是否有重复数据，有的话需要清掉
            LambdaQueryWrapper<CourierInfo> childQueryWrapper = new LambdaQueryWrapper<>();
            childQueryWrapper.in(CourierInfo::getCourierCode, courierCodeList);
            childQueryWrapper.eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
            childQueryWrapper.isNull(CourierInfo::getNextSiteId);
            List<CourierInfo> childCourierList = list(childQueryWrapper);
            if (CollectionUtil.isNotEmpty(childCourierList)) {
                List<Integer> childIdList = new ArrayList<>();
                for (CourierInfo courierInfo : childCourierList) {
                    childIdList.add(courierInfo.getId());
                }
                removeByIds(childIdList);
            }
            //主账号入库
            List<CourierInfo> courierToSaveList = new ArrayList<>();
            for (String courierCode : courierCodeList) {
                CourierInfo courierInfo = new CourierInfo();
                courierInfo.setCourierCode(courierCode);
                courierInfo.setNextSiteId(nextSiteId);
                courierInfo.setMainStorageImageUrl("");
                courierInfo.setUserPhone("");
                courierInfo.setUserPhoneHide(0);
                courierInfo.setSiteId(UserInfoUtil.getSiteId());
                courierInfo.setCourierName(CourierUtil.getCourierName(courierCode));
                courierInfo.setStorageTime(date);
                courierInfo.setCreateTime(date);
                courierInfo.setUpdateTime(date);
                if (subsiteIn != null && subsiteIn == 1) {
                    courierInfo.setDeliveryTime(date);
                } else {
                    courierInfo.setDeliveryTime(null);
                }
                courierInfo.setOperatorId(UserInfoUtil.getUserid());
                if (subsiteIn != null && subsiteIn == 1) {
                    courierInfo.setCourierStatus(CourierStatusEnum.DELIVERY.getCode());
                } else {
                    courierInfo.setCourierStatus(CourierStatusEnum.STORAGE.getCode());
                }
                courierToSaveList.add(courierInfo);
                if (subsiteIn != null && subsiteIn == 1) {
                    //子账号入库
                    CourierInfo subCourierInfo = new CourierInfo();
                    subCourierInfo.setCourierCode(courierCode);
                    subCourierInfo.setCourierName(CourierUtil.getCourierName(courierCode));
                    subCourierInfo.setCourierStatus(CourierStatusEnum.STORAGE.getCode());
                    subCourierInfo.setSiteId(nextSiteId);
                    subCourierInfo.setDeliveryTime(null);
                    subCourierInfo.setNextSiteId(null);
                    subCourierInfo.setSiteType(2);
                    subCourierInfo.setStorageImageUrl("");
                    subCourierInfo.setUserPhone("");
                    subCourierInfo.setUserPhoneHide(0);
                    subCourierInfo.setStorageTime(date);
                    subCourierInfo.setCreateTime(date);
                    subCourierInfo.setUpdateTime(date);
                    subCourierInfo.setOperatorId(UserInfoUtil.getUserid());
                    courierToSaveList.add(subCourierInfo);
                }
            }
            if (CollectionUtil.isNotEmpty(courierToSaveList)) {
                saveBatch(courierToSaveList, 3000);
            }
        }
        return true;
    }

    @Override
    public List<String> batchSaveChild(BatchDeliveryDTO batchDeliveryDTO) {
        if (CollectionUtils.isEmpty(batchDeliveryDTO.getCourierInfoList())) {
            throw new RuntimeException("参数不能为空");
        }
        try {
            //子站点id
            Integer siteId = UserInfoUtil.getSiteId();
            List<String> courierCodeList = new ArrayList<>();
            for (CourierInfoDTO courierInfoDTO : batchDeliveryDTO.getCourierInfoList()) {
                courierCodeList.add(courierInfoDTO.getCourierCode());
            }
            //查询主账号数据
            Map<String, CourierInfo> mainMap = new HashMap<>();
            LambdaQueryWrapper<CourierInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(CourierInfo::getCourierCode, courierCodeList);
            queryWrapper.isNotNull(CourierInfo::getNextSiteId);
            queryWrapper.eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
            List<CourierInfo> mainCourierList = list(queryWrapper);
            //主账号的状态更改为出库
            for (CourierInfo courierInfo : mainCourierList) {
                if (!CourierStatusEnum.DELIVERY.getCode().equals(courierInfo.getCourierStatus())) {
                    courierInfo.setCourierStatus(CourierStatusEnum.DELIVERY.getCode());
                    courierInfo.setNextSiteId(siteId);
                    courierInfo.setDeliveryTime(new Date());
                    courierInfo.setUpdateTime(new Date());
                    courierInfo.setRemark(batchDeliveryDTO.getRemark());
                }
                mainMap.put(courierInfo.getCourierCode(), courierInfo);
            }
            updateBatchById(mainCourierList);
            //查询子账号数据
            LambdaQueryWrapper<CourierInfo> childQueryWrapper = new LambdaQueryWrapper<>();
            childQueryWrapper.eq(CourierInfo::getSiteId, siteId);
            childQueryWrapper.isNull(CourierInfo::getNextSiteId);
            childQueryWrapper.in(CourierInfo::getCourierCode, courierCodeList);
            childQueryWrapper.eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
            List<CourierInfo> childCourierList = list(childQueryWrapper);
            List<String> repeatCodeList = new ArrayList<>();
            for (CourierInfo courierInfo : childCourierList) {
                if (!repeatCodeList.contains(courierInfo.getCourierCode())) {
                    repeatCodeList.add(courierInfo.getCourierCode());
                }
            }
            List<CourierInfo> childToSaveCourierList = new ArrayList<>();
            for (CourierInfoDTO courierInfoDTO : batchDeliveryDTO.getCourierInfoList()) {
                if (!repeatCodeList.contains(courierInfoDTO.getCourierCode())) {
                    Date date = new Date();
                    CourierInfo mainCourierInfo = mainMap.get(courierInfoDTO.getCourierCode());
                    CourierInfo childCourierInfo = new CourierInfo();
                    if (!TextUtils.isEmpty(courierInfoDTO.getUserName())) {
                        childCourierInfo.setUserName(courierInfoDTO.getUserName());
                    } else {
                        if (mainCourierInfo != null) {
                            childCourierInfo.setUserName(mainCourierInfo.getUserName());
                        }
                    }
                    if (!TextUtils.isEmpty(courierInfoDTO.getUserPhone())) {
                        childCourierInfo.setUserPhone(courierInfoDTO.getUserPhone());
                    } else {
                        if (mainCourierInfo != null) {
                            childCourierInfo.setUserPhone(mainCourierInfo.getUserPhone());
                        }
                    }
                    if (mainCourierInfo != null) {
                        childCourierInfo.setUserAddress(mainCourierInfo.getUserAddress());
                    }
                    if (!TextUtils.isEmpty(courierInfoDTO.getCourierName())) {
                        childCourierInfo.setCourierName(courierInfoDTO.getCourierName());
                    } else {
                        if (mainCourierInfo != null) {
                            childCourierInfo.setCourierName(mainCourierInfo.getCourierName());
                        }
                    }
                    childCourierInfo.setCourierCode(courierInfoDTO.getCourierCode());
                    childCourierInfo.setCourierStatus(CourierStatusEnum.STORAGE.getCode());
                    if (mainCourierInfo != null) {
                        childCourierInfo.setImageUrl(mainCourierInfo.getImageUrl());
                    }
                    childCourierInfo.setSiteId(UserInfoUtil.getSiteId());
                    childCourierInfo.setSiteType(SiteTypeEnum.NO_SUBSITE.getCode());
                    childCourierInfo.setStorageTime(date);
                    childCourierInfo.setCreateTime(date);
                    childCourierInfo.setUpdateTime(date);
                    childCourierInfo.setOperatorId(UserInfoUtil.getUserid());
                    if (mainCourierInfo != null) {
                        childCourierInfo.setSenderInfo(mainCourierInfo.getSenderInfo());
                    }
                    if (!TextUtils.isEmpty(courierInfoDTO.getRemark())) {
                        childCourierInfo.setRemark(courierInfoDTO.getRemark());
                    } else {
                        if (mainCourierInfo != null) {
                            childCourierInfo.setRemark(mainCourierInfo.getRemark());
                        }
                    }
                    childToSaveCourierList.add(childCourierInfo);
                }
            }
            saveOrUpdateBatch(childToSaveCourierList);
            return repeatCodeList;
        } catch (Exception e) {
            log.info("e ======== " + e);
        }
        return null;
    }

    @Override
    @Transactional
    public Boolean batchDelivery(DeliveryDTO deliveryDTO) {
        if (CollectionUtils.isEmpty(deliveryDTO.getCourierCodeList())) {
            throw new RuntimeException("参数不能为空");
        }
        CourierSite courierSite = courierSiteService.getById(UserInfoUtil.getSiteId());

        //入库
        if (BatchOperateEnum.STORAGE.getCode().equals(deliveryDTO.getType())) {
            storage(deliveryDTO, courierSite);
        }
        //出库
        if (BatchOperateEnum.DELIVERY.getCode().equals(deliveryDTO.getType())) {
            delivery(deliveryDTO);

        }
        //撤销出库
        if (BatchOperateEnum.REVOKE_DELIVERY.getCode().equals(deliveryDTO.getType())) {
            revokeDelivery(deliveryDTO);
        }
        //退件出库
        if (BatchOperateEnum.RETURN_DELIVERY.getCode().equals(deliveryDTO.getType())) {
            returnDelivery(deliveryDTO);
        }
        //退件入库
        if (BatchOperateEnum.RETURN_STORAGE.getCode().equals(deliveryDTO.getType())) {
            returnDelivery(deliveryDTO);
        }

        return true;
    }

    private void returnStorage(DeliveryDTO deliveryDTO) {
        for (String courierCode : deliveryDTO.getCourierCodeList()) {
            LambdaQueryWrapper<CourierInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CourierInfo::getCourierCode, courierCode);
            queryWrapper.eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
            queryWrapper.eq(CourierInfo::getSiteId, UserInfoUtil.getSiteId());
            CourierInfo courierInfo = getOne(queryWrapper);
            if (Objects.isNull(courierInfo)) {
                throw new RuntimeException("快递信息不存在");
            }
            courierInfo.setCourierStatus(CourierStatusEnum.RETURN_DELIVERY.getCode());
            courierInfo.setDeliveryTime(new Date());
            courierInfo.setUpdateTime(new Date());
            courierInfo.setRemark(deliveryDTO.getRemark());
            updateById(courierInfo);
            if (Objects.isNull(courierInfo.getNextSiteId())) {
                LambdaQueryWrapper<CourierInfo> parentqQueryWrapper = new LambdaQueryWrapper<>();
                parentqQueryWrapper.eq(CourierInfo::getCourierCode, courierCode);
                parentqQueryWrapper.eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
                parentqQueryWrapper.eq(CourierInfo::getNextSiteId, courierInfo.getSiteId());
                CourierInfo parentCourierInfo = getOne(parentqQueryWrapper);
                if (Objects.nonNull(parentCourierInfo)) {
                    parentCourierInfo.setUpdateTime(new Date());
                    parentCourierInfo.setStorageTime(new Date());
                    parentCourierInfo.setCourierStatus(CourierStatusEnum.RETURN_STORAGE.getCode());
                    updateById(parentCourierInfo);
                }
            } else {
                //主账号 退件出库子账号删除
                LambdaQueryWrapper<CourierInfo> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(CourierInfo::getCourierCode, courierCode);
                wrapper.eq(CourierInfo::getSiteId, courierInfo.getNextSiteId());
                remove(wrapper);
            }
        }
    }

    private void returnDelivery(DeliveryDTO deliveryDTO) {
        for (String courierCode : deliveryDTO.getCourierCodeList()) {
            LambdaQueryWrapper<CourierInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CourierInfo::getCourierCode, courierCode);
            queryWrapper.eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
            queryWrapper.eq(CourierInfo::getSiteId, UserInfoUtil.getSiteId());
            CourierInfo courierInfo = getOne(queryWrapper);
            if (Objects.isNull(courierInfo)) {
                throw new RuntimeException("快递信息不存在");
            }
            if (BatchOperateEnum.RETURN_STORAGE.getCode().equals(deliveryDTO.getType())) {
                remove(queryWrapper);
            } else {
                courierInfo.setCourierStatus(CourierStatusEnum.RETURN_DELIVERY.getCode());
                courierInfo.setDeliveryTime(new Date());
                courierInfo.setUpdateTime(new Date());
                courierInfo.setRemark(deliveryDTO.getRemark());
                updateById(courierInfo);
                if (Objects.isNull(courierInfo.getNextSiteId())) {
                    LambdaQueryWrapper<CourierInfo> parentqQueryWrapper = new LambdaQueryWrapper<>();
                    parentqQueryWrapper.eq(CourierInfo::getCourierCode, courierCode);
                    parentqQueryWrapper.eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
                    parentqQueryWrapper.eq(CourierInfo::getNextSiteId, courierInfo.getSiteId());
                    CourierInfo parentCourierInfo = getOne(parentqQueryWrapper);
                    if (Objects.nonNull(parentCourierInfo)) {
                        parentCourierInfo.setUpdateTime(new Date());
                        parentCourierInfo.setStorageTime(new Date());
                        parentCourierInfo.setCourierStatus(CourierStatusEnum.RETURN_STORAGE.getCode());
                        updateById(parentCourierInfo);
                    }
                } else {
                    //主账号 退件出库子账号删除
                    LambdaQueryWrapper<CourierInfo> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(CourierInfo::getCourierCode, courierCode);
                    wrapper.eq(CourierInfo::getSiteId, courierInfo.getNextSiteId());
                    remove(wrapper);
                }
            }
        }
    }

    private void revokeDelivery(DeliveryDTO deliveryDTO) {
        for (String courierCode : deliveryDTO.getCourierCodeList()) {
            LambdaQueryWrapper<CourierInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CourierInfo::getCourierCode, courierCode);
            queryWrapper.eq(CourierInfo::getSiteId, UserInfoUtil.getSiteId());
            queryWrapper.eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
            CourierInfo courierInfo = getOne(queryWrapper);
            if (Objects.isNull(courierInfo)) {
                throw new RuntimeException("快递信息不存在");
            }
            courierInfo.setCourierStatus(CourierStatusEnum.STORAGE.getCode());
            courierInfo.setStorageTime(new Date());
            courierInfo.setUpdateTime(new Date());
            courierInfo.setRemark(deliveryDTO.getRemark());
            updateById(courierInfo);
            if (Objects.nonNull(courierInfo.getNextSiteId())) {
                //子节点入库
                LambdaQueryWrapper<CourierInfo> queryWrapperOne = new LambdaQueryWrapper<>();
                queryWrapperOne.eq(CourierInfo::getCourierCode, courierCode);
                queryWrapperOne.eq(CourierInfo::getSiteId, courierInfo.getNextSiteId());
                queryWrapperOne.eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
                remove(queryWrapperOne);
            }

        }
    }

    private void delivery(DeliveryDTO deliveryDTO) {
        for (String courierCode : deliveryDTO.getCourierCodeList()) {
            LambdaQueryWrapper<CourierInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CourierInfo::getCourierCode, courierCode);
            queryWrapper.eq(CourierInfo::getSiteId, UserInfoUtil.getSiteId());
            queryWrapper.eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
            CourierInfo courierInfo = getOne(queryWrapper);
            if (Objects.isNull(courierInfo)) {
                throw new RuntimeException("快递信息不存在");
            }
            if (Objects.nonNull(courierInfo.getNextSiteId())) {
                courierInfo.setCourierStatus(CourierStatusEnum.DELIVERY.getCode());
            } else {
                courierInfo.setCourierStatus(CourierStatusEnum.HAVE_RECEIVED.getCode());
            }
            courierInfo.setDeliveryTime(new Date());
            courierInfo.setUpdateTime(new Date());
            courierInfo.setRemark(deliveryDTO.getRemark());
            updateById(courierInfo);
            if (Objects.nonNull(courierInfo.getNextSiteId())) {
                //子节点入库
                CourierInfo subSiteCourierInfo = new CourierInfo();
                subSiteCourierInfo.setUserName(courierInfo.getUserName());
                subSiteCourierInfo.setUserPhone(courierInfo.getUserPhone());
                subSiteCourierInfo.setUserAddress(courierInfo.getUserAddress());
                subSiteCourierInfo.setCourierName(courierInfo.getCourierName());
                subSiteCourierInfo.setCourierCode(courierInfo.getCourierCode());
                subSiteCourierInfo.setCourierStatus(CourierStatusEnum.STORAGE.getCode());
                subSiteCourierInfo.setImageUrl(courierInfo.getImageUrl());
                subSiteCourierInfo.setSiteId(courierInfo.getNextSiteId());
                subSiteCourierInfo.setSiteType(SiteTypeEnum.NO_SUBSITE.getCode());
                subSiteCourierInfo.setStorageTime(new Date());
                subSiteCourierInfo.setCreateTime(new Date());
                subSiteCourierInfo.setUpdateTime(new Date());
                subSiteCourierInfo.setOperatorId(UserInfoUtil.getUserid());
                subSiteCourierInfo.setSenderInfo(courierInfo.getSenderInfo());
                subSiteCourierInfo.setDeliveryTime(new Date());
                subSiteCourierInfo.setRemark(courierInfo.getRemark());
                save(subSiteCourierInfo);
            }

        }
    }

    private void storage(DeliveryDTO deliveryDTO, CourierSite courierSite) {
        if (courierSite.getParentId() == 0) {
            for (String courierCode : deliveryDTO.getCourierCodeList()) {
                LambdaQueryWrapper<CourierInfo> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(CourierInfo::getCourierCode, courierCode);
                queryWrapper.eq(CourierInfo::getSiteId, UserInfoUtil.getSiteId());
                queryWrapper.eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
                CourierInfo courierInfo = getOne(queryWrapper);
                if (Objects.isNull(courierInfo)) {
                    throw new RuntimeException("快递信息不存在");
                }
                courierInfo.setCourierStatus(CourierStatusEnum.STORAGE.getCode());
                courierInfo.setStorageTime(new Date());
                courierInfo.setUpdateTime(new Date());
                courierInfo.setRemark(deliveryDTO.getRemark());
                updateById(courierInfo);
            }
        } else {
            for (String courierCode : deliveryDTO.getCourierCodeList()) {
                LambdaQueryWrapper<CourierInfo> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(CourierInfo::getCourierCode, courierCode);
                queryWrapper.eq(CourierInfo::getNextSiteId, UserInfoUtil.getSiteId());
                queryWrapper.eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
                CourierInfo courierInfo = getOne(queryWrapper);
                if (Objects.isNull(courierInfo)) {
                    throw new RuntimeException("快递信息不存在");
                }
                if (!CourierStatusEnum.DELIVERY.getCode().equals(courierInfo.getCourierStatus())) {
                    courierInfo.setCourierStatus(CourierStatusEnum.DELIVERY.getCode());
                    courierInfo.setDeliveryTime(new Date());
                    courierInfo.setUpdateTime(new Date());
                    courierInfo.setRemark(deliveryDTO.getRemark());
                    updateById(courierInfo);
                }
                Date date = new Date();
                CourierInfo childCourierInfo = new CourierInfo();
                childCourierInfo.setUserName(courierInfo.getUserName());
                childCourierInfo.setUserPhone(courierInfo.getUserPhone());
                childCourierInfo.setUserAddress(courierInfo.getUserAddress());
                childCourierInfo.setCourierName(courierInfo.getCourierName());
                childCourierInfo.setCourierCode(courierInfo.getCourierCode());
                childCourierInfo.setCourierStatus(CourierStatusEnum.STORAGE.getCode());
                childCourierInfo.setImageUrl(courierInfo.getImageUrl());
                childCourierInfo.setSiteId(UserInfoUtil.getSiteId());
                childCourierInfo.setSiteType(SiteTypeEnum.NO_SUBSITE.getCode());
                childCourierInfo.setStorageTime(date);
                childCourierInfo.setCreateTime(date);
                childCourierInfo.setUpdateTime(date);
                childCourierInfo.setOperatorId(UserInfoUtil.getUserid());
                childCourierInfo.setSenderInfo(courierInfo.getSenderInfo());
                childCourierInfo.setRemark(courierInfo.getRemark());

                LambdaQueryWrapper<CourierInfo> childQueryWrapper = new LambdaQueryWrapper<>();
                childQueryWrapper.eq(CourierInfo::getId, UserInfoUtil.getSiteId());
                childQueryWrapper.eq(CourierInfo::getCourierCode, courierInfo.getCourierCode());
                childQueryWrapper.eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());

                saveOrUpdate(childCourierInfo, childQueryWrapper);

            }
        }

    }

    @Override
    public Boolean delete(String id, Integer type) {

        CourierSite site = courierSiteService.getById(UserInfoUtil.getSiteId());

        CourierInfo courierInfo = getById(id);

        if (site.getParentId() == 0) {
            //撤销入库
            if (type == 1) {
                removeById(id);
            }
            if (type == 2) {
                //主站点修改为入库
                courierInfo.setCourierStatus(CourierStatusEnum.STORAGE.getCode());
                updateById(courierInfo);

                //子站点删除
                LambdaQueryWrapper<CourierInfo> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(CourierInfo::getSiteId, courierInfo.getNextSiteId());
                remove(queryWrapper);

            }

        } else {
            if (type == 2) {
                //主站点修改为入库
                courierInfo.setCourierStatus(CourierStatusEnum.STORAGE.getCode());
                updateById(courierInfo);

            }
            //撤销入库
            if (type == 1) {
                //子站点删除
                removeById(id);
                //主站点修改入库状态
                LambdaUpdateWrapper<CourierInfo> queryWrapper = new LambdaUpdateWrapper<>();
                queryWrapper.eq(CourierInfo::getNextSiteId, courierInfo.getNextSiteId());
                queryWrapper.eq(CourierInfo::getCourierCode, courierInfo.getCourierCode());
                queryWrapper.set(CourierInfo::getCourierStatus, CourierStatusEnum.STORAGE.getCode());
                update(queryWrapper);
            }
        }
        return true;
    }

    @Override
    @Transactional
    public CourierInfo delivery(CourierInfoDTO courierInfoDTO) throws Exception {
        try {
            log.info("出库请求参数:{}", JsonUtils.toJson(courierInfoDTO));
            LambdaQueryWrapper<CourierInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CourierInfo::getCourierCode, courierInfoDTO.getCourierCode());
            log.info("出库请求参数 UserInfoUtil.getUserType():{}", UserInfoUtil.getUserType());
            if (UserInfoUtil.getUserType() == 2 && Objects.nonNull(courierInfoDTO.getNextSiteId())) {
                queryWrapper.eq(CourierInfo::getSiteId, courierInfoDTO.getNextSiteId());
            } else {
                queryWrapper.eq(CourierInfo::getSiteId, UserInfoUtil.getSiteId());
            }
            CourierInfo courierInfo = getOne(queryWrapper);
            if (Objects.isNull(courierInfo)) {
                log.info("快递信息不存在");
                throw new RuntimeException("快递信息不存在");
            } else {
                log.info("courierInfo{}", JsonUtils.toJson(courierInfo));
            }
//        if (Objects.isNull(courierInfoDTO.getNextSiteId())) {
//            courierInfoDTO.setNextSiteId(UserInfoUtil.getNextSiteId());
//        }
            if (Objects.nonNull(courierInfo.getNextSiteId())) {
                if (Objects.isNull(courierInfoDTO.getNextSiteId())) {
                    throw new BusinessException("nextSiteId not null");
                } else {
                    if (!courierInfo.getNextSiteId().equals(courierInfoDTO.getNextSiteId())) {
                        throw new BusinessException("快件错分，请妥善保管");
                    }
                }
            }
            Integer nextSiteId = courierInfo.getNextSiteId();
            if (courierInfo.getCourierStatus().equals(CourierStatusEnum.RETURN_STORAGE.getCode())) {
                if (Objects.isNull(courierInfoDTO.getNextSiteId())) {
                    throw new BusinessException("再分配操作 nextSiteId 不能为空");
                }
                nextSiteId = courierInfoDTO.getNextSiteId();
                courierInfo.setNextSiteId(nextSiteId);
            }
            if (StringUtils.isNotBlank(courierInfoDTO.getUserPhone())) {
                courierInfo.setUserPhone(courierInfoDTO.getUserPhone());
            }


            if (CourierStatusEnum.DELIVERY.getCode().equals(courierInfo.getCourierStatus()) || CourierStatusEnum.HAVE_RECEIVED.getCode().equals(courierInfo.getCourierStatus())) {
                log.info("已出库,请勿重复出库");
                throw new RuntimeException("已出库,请勿重复出库");
            }
            courierInfo.setDeliveryTime(new Date());
            courierInfo.setUpdateTime(new Date());
            log.info("courierInfo.getNextSiteId() ==== " + courierInfo.getNextSiteId());
            if (Objects.nonNull(courierInfo.getNextSiteId())) {
                courierInfo.setCourierStatus(CourierStatusEnum.DELIVERY.getCode());
            } else {
                courierInfo.setCourierStatus(CourierStatusEnum.HAVE_RECEIVED.getCode());
            }

            updateById(courierInfo);

            if (Objects.nonNull(courierInfo.getNextSiteId())) {
                log.info("子节点入库");
                LambdaQueryWrapper<CourierInfo> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(CourierInfo::getCourierCode, courierInfoDTO.getCourierCode());
                wrapper.eq(CourierInfo::getSiteId, nextSiteId);
                wrapper.eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
                CourierInfo subSiteCourierInfo = getOne(wrapper);

                if (Objects.nonNull(subSiteCourierInfo)) {
                    log.info("子节点入库 courierInfo");
                    return courierInfo;
                }
                //子节点入库
                subSiteCourierInfo = new CourierInfo();
                Date date = new Date();

                subSiteCourierInfo.setUserName(courierInfo.getUserName());
                subSiteCourierInfo.setUserPhone(courierInfo.getUserPhone());
                subSiteCourierInfo.setUserAddress(courierInfo.getUserAddress());
                subSiteCourierInfo.setCourierName(courierInfo.getCourierName());
                subSiteCourierInfo.setCourierCode(courierInfo.getCourierCode());
                subSiteCourierInfo.setCourierStatus(CourierStatusEnum.STORAGE.getCode());
                subSiteCourierInfo.setImageUrl(courierInfo.getImageUrl());
                subSiteCourierInfo.setSiteId(nextSiteId);
                subSiteCourierInfo.setSiteType(SiteTypeEnum.NO_SUBSITE.getCode());
                subSiteCourierInfo.setStorageTime(date);
                subSiteCourierInfo.setCreateTime(date);
                subSiteCourierInfo.setUpdateTime(date);
                subSiteCourierInfo.setOperatorId(UserInfoUtil.getUserid());
                subSiteCourierInfo.setSenderInfo(courierInfo.getSenderInfo());
                subSiteCourierInfo.setRemark(courierInfo.getRemark());

                save(subSiteCourierInfo);
            }
            CourierSite courierSite = courierSiteService.getById(UserInfoUtil.getSiteId());

            if (StringUtils.isNotBlank(courierInfo.getUserPhone())) {
                if (courierSite.getParentId() == 0) {
                    if (Objects.nonNull(courierInfo.getNextSiteId())) {
                        CourierSite nextCourierSite = courierSiteService.getById(courierInfoDTO.getNextSiteId());
                        push(courierInfo.getUserPhone(), "4", courierInfo.getCourierName(), courierInfo.getCourierCode(), nextCourierSite.getSiteName(), nextCourierSite.getSiteAddress(), nextCourierSite.getPhone());
                    }
                } else {
                    push(courierInfo.getUserPhone(), "3", courierInfo.getCourierName(), courierInfo.getCourierCode(), courierSite.getSiteName(), courierInfo.getUserAddress(), courierSite.getPhone());
                }
            }

            return courierInfo;
        } catch (Exception e) {
            log.info("e ---> " + e.getMessage());
            throw new BusinessException(e.getMessage());
        }
    }

    @Override
    public List<CourierInfo> messageList(CourierInfoListQueryDTO courierInfoListQueryDTO) throws Exception {
        LambdaQueryWrapper<CourierInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(Objects.nonNull(courierInfoListQueryDTO.getAdviceStatus()), CourierInfo::getAdviceStatus, courierInfoListQueryDTO.getAdviceStatus())
                .eq(Objects.nonNull(courierInfoListQueryDTO.getUserPhoneHide()), CourierInfo::getUserPhoneHide, courierInfoListQueryDTO.getUserPhoneHide())
                .orderByDesc(CourierInfo::getUpdateTime);
        if (StringUtils.isNotBlank(courierInfoListQueryDTO.getStartTime())) {
            queryWrapper.gt(StringUtils.isNotBlank(courierInfoListQueryDTO.getStartTime()), CourierInfo::getUpdateTime, courierInfoListQueryDTO.getStartTime());
        }
        if (StringUtils.isNotBlank(courierInfoListQueryDTO.getEndTime())) {
            queryWrapper.lt(StringUtils.isNotBlank(courierInfoListQueryDTO.getEndTime()), CourierInfo::getUpdateTime, courierInfoListQueryDTO.getEndTime());
        }
        queryWrapper.eq(CourierInfo::getCourierStatus, courierInfoListQueryDTO.getCourierStatus());
        System.out.println("UserInfoUtil.getSiteId() ===== ");
        System.out.println(UserInfoUtil.getSiteId());
        System.out.println(courierInfoListQueryDTO.getCourierStatus());
        queryWrapper.eq(CourierInfo::getSiteId, UserInfoUtil.getSiteId());
        List<CourierInfo> courierInfoList = list(queryWrapper);
        return courierInfoList;
    }


    @Override
    public Page<CourierInfoDetailVO> list(CourierInfoListQueryDTO courierInfoListQueryDTO) throws Exception {
        CourierSite site = courierSiteService.getById(UserInfoUtil.getSiteId());
        LambdaQueryWrapper<CourierInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(StringUtils.isNotBlank(courierInfoListQueryDTO.getCourierCode()), CourierInfo::getCourierCode, courierInfoListQueryDTO.getCourierCode())
                .like(StringUtils.isNotBlank(courierInfoListQueryDTO.getUserName()), CourierInfo::getUserName, courierInfoListQueryDTO.getUserName())
                .like(StringUtils.isNotBlank(courierInfoListQueryDTO.getUserPhone()), CourierInfo::getUserPhone, courierInfoListQueryDTO.getUserPhone())
                .eq(Objects.nonNull(courierInfoListQueryDTO.getAdviceStatus()), CourierInfo::getAdviceStatus, courierInfoListQueryDTO.getAdviceStatus())
                .orderByDesc(CourierInfo::getUpdateTime);
        if (StringUtils.isNotBlank(courierInfoListQueryDTO.getStartTime())) {
            queryWrapper.gt(StringUtils.isNotBlank(courierInfoListQueryDTO.getStartTime()), CourierInfo::getUpdateTime, courierInfoListQueryDTO.getStartTime());
        }
        if (StringUtils.isNotBlank(courierInfoListQueryDTO.getEndTime())) {
            queryWrapper.lt(StringUtils.isNotBlank(courierInfoListQueryDTO.getEndTime()), CourierInfo::getUpdateTime, courierInfoListQueryDTO.getEndTime());
        }
        if (StringUtils.isNotBlank(courierInfoListQueryDTO.getKeyword())) {
            queryWrapper.and(wr -> wr
                    .like(CourierInfo::getCourierCode, courierInfoListQueryDTO.getKeyword())
                    .or()
                    .like(CourierInfo::getUserName, courierInfoListQueryDTO.getKeyword())
                    .or()
                    .like(CourierInfo::getUserPhone, courierInfoListQueryDTO.getKeyword())

            );
        }
        if (courierInfoListQueryDTO.getType() == 1) {
            String appSite = UserInfoUtil.getAppSite();
            log.info("appSite --> {}", appSite);
            List<Integer> appSiteList = new ArrayList<>();
            if (!TextUtils.isEmpty(appSite)) {
                if (appSite.contains(",")) {
                    String[] list = appSite.split(",");
                    for (int i = 0; i < list.length; i++) {
                        appSiteList.add(Integer.parseInt(list[i]));
                    }
                } else {
                    appSiteList.add(Integer.parseInt(appSite));
                }
            }
            if (appSiteList != null && !appSiteList.isEmpty()) {
                queryWrapper.in(CourierInfo::getNextSiteId, appSiteList);
            }
            queryWrapper.eq(Objects.nonNull(courierInfoListQueryDTO.getCourierStatus()) && !courierInfoListQueryDTO.getCourierStatus().equals(0), CourierInfo::getCourierStatus, courierInfoListQueryDTO.getCourierStatus());
            queryWrapper.eq(Objects.nonNull(courierInfoListQueryDTO.getNextSiteId()), CourierInfo::getNextSiteId, courierInfoListQueryDTO.getNextSiteId());
            queryWrapper.eq(CourierInfo::getSiteId, UserInfoUtil.getSiteId());
        } else {
            if (CourierStatusEnum.TO_BE_STORED.getCode().equals(courierInfoListQueryDTO.getCourierStatus())) {
                queryWrapper.eq(CourierInfo::getCourierStatus, CourierStatusEnum.STORAGE.getCode());
                if (UserInfoUtil.getUserType() == 2) {
                    queryWrapper.eq(CourierInfo::getNextSiteId, courierInfoListQueryDTO.getNextSiteId());
                } else {
                    queryWrapper.eq(CourierInfo::getNextSiteId, UserInfoUtil.getSiteId());
                }
            } else {
                if (courierInfoListQueryDTO.getCourierStatus() == 0) {
                    queryWrapper.and(wrapper -> wrapper
                            .and(wrapp -> wrapp
                                    .eq(CourierInfo::getSiteId, UserInfoUtil.getSiteId()))
                            .or(wrappe -> wrappe
                                    .eq(CourierInfo::getNextSiteId, UserInfoUtil.getSiteId())
                                    .eq(CourierInfo::getCourierStatus, CourierStatusEnum.STORAGE.getCode())));
                } else {
                    queryWrapper.eq(CourierInfo::getCourierStatus, courierInfoListQueryDTO.getCourierStatus());
                    queryWrapper.eq(CourierInfo::getSiteId, UserInfoUtil.getSiteId());
                }
            }

        }


        Page<CourierInfo> page = new Page<>();
        page.setCurrent(courierInfoListQueryDTO.getCurrent());
        page.setSize(courierInfoListQueryDTO.getSize());
        Page pageList = page(page, queryWrapper);

        List<CourierInfo> records = pageList.getRecords();

        //查询主账号数据
        LambdaQueryWrapper<CourierInfo> query = new LambdaQueryWrapper<>();
        query.isNotNull(CourierInfo::getNextSiteId)
                .eq(StringUtils.isNotBlank(courierInfoListQueryDTO.getCourierCode()), CourierInfo::getCourierCode, courierInfoListQueryDTO.getCourierCode())
                .like(StringUtils.isNotBlank(courierInfoListQueryDTO.getUserName()), CourierInfo::getUserName, courierInfoListQueryDTO.getUserName())
                .like(StringUtils.isNotBlank(courierInfoListQueryDTO.getUserPhone()), CourierInfo::getUserPhone, courierInfoListQueryDTO.getUserPhone())
                .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
        if (StringUtils.isNotBlank(courierInfoListQueryDTO.getStartTime())) {
            query.gt(StringUtils.isNotBlank(courierInfoListQueryDTO.getStartTime()), CourierInfo::getUpdateTime, courierInfoListQueryDTO.getStartTime());
        }
        if (StringUtils.isNotBlank(courierInfoListQueryDTO.getEndTime())) {
            query.lt(StringUtils.isNotBlank(courierInfoListQueryDTO.getEndTime()), CourierInfo::getUpdateTime, courierInfoListQueryDTO.getEndTime());
        }
        List<CourierInfo> mainCourierInfoList = list(query);

        List<CourierInfoDetailVO> courierInfoDetailVOList = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(records)) {
            for (CourierInfo courierInfo : records) {
                CourierInfoDetailVO courierInfoDetailVO = new CourierInfoDetailVO();
                BeanUtils.copyProperties(courierInfo, courierInfoDetailVO);

                CourierSite courierSite = new CourierSite();

                if (Objects.isNull(courierInfo.getNextSiteId())) {
                    LambdaQueryWrapper<CourierInfo> parentQueryWrapper = new LambdaQueryWrapper<>();
                    parentQueryWrapper.eq(CourierInfo::getCourierCode, courierInfo.getCourierCode());
                    parentQueryWrapper.isNotNull(CourierInfo::getNextSiteId).last("limit 1");
                    CourierInfo parentCourierInfo = getOne(parentQueryWrapper);
                    if (Objects.nonNull(parentCourierInfo)) {
                        courierInfoDetailVO.setReturnCompletionTime(parentCourierInfo.getDeliveryTime());
                    }
                } else {
                    courierInfoDetailVO.setReturnCompletionTime(courierInfo.getDeliveryTime());
                }

                if (Objects.nonNull(courierInfo.getNextSiteId())) {
                    courierSite = courierSiteService.getById(courierInfo.getNextSiteId());
                    courierInfoDetailVO.setSiteName(Objects.nonNull(courierSite) ? courierSite.getSiteName() : null);
                    if (site.getParentId() != 0) {
                        courierInfoDetailVO.setCourierStatus(6);
                        courierInfoDetailVO.setSiteName(site.getSiteName());
                    }
                }
                if (site.getParentId() != 0) {
                    courierInfoDetailVO.setSiteName(site.getSiteName());
                }
                Date date = new Date();
                String today = DateUtil.DateToString(date, DateUtil.DATE_FORMAT_YYYY_MM_DD);
                String storageTime = DateUtil.DateToString(courierInfo.getStorageTime(), DateUtil.DATE_FORMAT_YYYY_MM_DD);
                long storageDays = DateUtil.getDaySub(storageTime, today);

                courierInfoDetailVO.setStorageDays(storageDays);
                courierInfoDetailVO.setMessageAdviceStatus(courierInfo.getAdviceStatus());
                courierInfoDetailVO.setMainStorageTime(courierInfo.getStorageTime());
                for (CourierInfo mainCourierInfo : mainCourierInfoList) {
                    if (mainCourierInfo.getCourierCode().equals(courierInfo.getCourierCode())) {
                        courierInfoDetailVO.setMainStorageTime(mainCourierInfo.getStorageTime());
                        break;
                    }
                }

                courierInfoDetailVOList.add(courierInfoDetailVO);
            }

        }
        return pageList.setRecords(courierInfoDetailVOList);
    }

    @Override
    public ScanStatisticsVO scanStatistics(ScanStatisticsDTO scanStatisticsDTO) {
        ScanStatisticsVO scanStatisticsVO = new ScanStatisticsVO();
        String userName = UserInfoUtil.getUserName();
        UserInfo userInfo = userInfoService.findByUsername(userName, 1);
        if (Objects.nonNull(userInfo)) {
            CourierSite courierSite = courierSiteService.getById(userInfo.getSiteId());
            if (Objects.nonNull(courierSite)) {
                scanStatisticsVO.setSiteName(courierSite.getSiteName());
            }
        }
        String today = DateUtil.DateToString(new Date(), DateUtil.DATE_FORMAT_YYYY_MM_DD);
        if (scanStatisticsDTO.getType() == 1) {


            LambdaQueryWrapper<CourierInfo> storageueryWrapper = new LambdaQueryWrapper<>();
            storageueryWrapper
                    .eq(Objects.isNull(scanStatisticsDTO.getSiteId()), CourierInfo::getSiteId, UserInfoUtil.getSiteId())
                    .eq(Objects.nonNull(scanStatisticsDTO.getSiteId()), CourierInfo::getNextSiteId, scanStatisticsDTO.getSiteId())
                    .like(CourierInfo::getStorageTime, today)
                    .eq(CourierInfo::getCourierStatus, CourierStatusEnum.STORAGE.getCode());
            //今日入库数量
            int storageCount = count(storageueryWrapper);
            scanStatisticsVO.setStorageQuantity(storageCount);

        }
        if (scanStatisticsDTO.getType() == 2) {
            //出库
            LambdaQueryWrapper<CourierInfo> deliveryQueryWrapper = new LambdaQueryWrapper<>();
            deliveryQueryWrapper
                    .eq(Objects.isNull(scanStatisticsDTO.getSiteId()), CourierInfo::getSiteId, UserInfoUtil.getSiteId())
                    .eq(Objects.nonNull(scanStatisticsDTO.getSiteId()), CourierInfo::getNextSiteId, scanStatisticsDTO.getSiteId())
                    .like(CourierInfo::getUpdateTime, today)
                    .eq(CourierInfo::getCourierStatus, CourierStatusEnum.DELIVERY.getCode())
                    .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());

            int deliveryCount = count(deliveryQueryWrapper);
            scanStatisticsVO.setDeliveryQuantity(deliveryCount);

            //剩余
            LambdaQueryWrapper<CourierInfo> storageQueryWrapper = new LambdaQueryWrapper<>();
            storageQueryWrapper
                    .eq(Objects.isNull(scanStatisticsDTO.getSiteId()), CourierInfo::getSiteId, UserInfoUtil.getSiteId())
                    .eq(Objects.nonNull(scanStatisticsDTO.getSiteId()), CourierInfo::getNextSiteId, scanStatisticsDTO.getSiteId())
                    .eq(CourierInfo::getCourierStatus, CourierStatusEnum.STORAGE.getCode())
                    .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());

            int laveQuantity = count(storageQueryWrapper);
            scanStatisticsVO.setLaveQuantity(laveQuantity);

        }
        if (scanStatisticsDTO.getType() == 3) {

            //今日已入库数
            LambdaQueryWrapper<CourierInfo> todayStorageQueryWrapper = new LambdaQueryWrapper<>();
            todayStorageQueryWrapper
                    .eq(Objects.isNull(scanStatisticsDTO.getSiteId()), CourierInfo::getSiteId, UserInfoUtil.getSiteId())
                    .like(CourierInfo::getStorageTime, today)
                    .eq(CourierInfo::getCourierStatus, CourierStatusEnum.STORAGE.getCode())
                    .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
            //今日入库数量
            int todayStorageQuantity = count(todayStorageQueryWrapper);
            scanStatisticsVO.setTodayStorageQuantity(todayStorageQuantity);

            //入库
            LambdaQueryWrapper<CourierInfo> storageQueryWrapper = new LambdaQueryWrapper<>();
            storageQueryWrapper.eq(CourierInfo::getSiteId, UserInfoUtil.getSiteId())
                    .eq(CourierInfo::getCourierStatus, CourierStatusEnum.STORAGE.getCode())
                    .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());

            int storageCount = count(storageQueryWrapper);
            scanStatisticsVO.setStorageQuantity(storageCount);

            //剩余
            LambdaQueryWrapper<CourierInfo> laveQueryWrapper = new LambdaQueryWrapper<>();
            laveQueryWrapper.eq(CourierInfo::getNextSiteId, UserInfoUtil.getSiteId())
                    .eq(CourierInfo::getCourierStatus, CourierStatusEnum.STORAGE.getCode())
                    .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());

            int laveCount = count(laveQueryWrapper);
            scanStatisticsVO.setLaveQuantity(laveCount);

        }

        if (scanStatisticsDTO.getType() == 4) {

            //出库
            LambdaQueryWrapper<CourierInfo> deliveryQueryWrapper = new LambdaQueryWrapper<>();
            deliveryQueryWrapper.eq(CourierInfo::getSiteId, UserInfoUtil.getSiteId())
                    .like(CourierInfo::getUpdateTime, today)
                    .eq(CourierInfo::getCourierStatus, CourierStatusEnum.HAVE_RECEIVED.getCode())
                    .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());

            int deliveryCount = count(deliveryQueryWrapper);
            scanStatisticsVO.setDeliveryQuantity(deliveryCount);

            //剩余
            LambdaQueryWrapper<CourierInfo> laveQueryWrapper = new LambdaQueryWrapper<>();
            laveQueryWrapper.eq(CourierInfo::getSiteId, UserInfoUtil.getSiteId())
                    .eq(CourierInfo::getCourierStatus, CourierStatusEnum.STORAGE.getCode())
                    .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());

            int laveCount = count(laveQueryWrapper);
            scanStatisticsVO.setLaveQuantity(laveCount);

        }
        return scanStatisticsVO;

    }

    @Override
    public void getExcel(HttpServletResponse response) throws Exception {
        LambdaQueryWrapper<CourierInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourierInfo::getSiteId, UserInfoUtil.getSiteId())
                .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());

        String today = DateUtil.DateToString(new Date(), DateUtil.DATE_FORMAT_YYYY_MM_DD);
        CourierInfoExcelQueryDTO courierInfoExcelQueryDTO = new CourierInfoExcelQueryDTO();
        courierInfoExcelQueryDTO.setStorageTime(today);
        courierInfoExcelQueryDTO.setSiteId(UserInfoUtil.getSiteId());
        List<CourierInfoExcelDTO> courierInfoList = courierInfoMapper.courierInfList(courierInfoExcelQueryDTO);


        List<CourierSiteExcelDTO> courierSiteExcelDTOList = Lists.newArrayList();
        CourierSiteExcelDTO courierSiteExcelDTO = new CourierSiteExcelDTO();
        courierSiteExcelDTOList.add(courierSiteExcelDTO);
        courierSiteExcelDTO.setSiteName("子账号名称");
        if (CollectionUtil.isNotEmpty(courierInfoList)) {
            Map<String, Long> map = courierInfoList.stream()
                    .collect(Collectors.groupingBy(CourierInfoExcelDTO::getSiteName, Collectors.counting()));

            Set<String> set = map.keySet();
            for (String siteName : set) {
                courierSiteExcelDTO = new CourierSiteExcelDTO();
                courierSiteExcelDTO.setSiteName(siteName);
                courierSiteExcelDTO.setCount(map.get(siteName).intValue());
                courierSiteExcelDTOList.add(courierSiteExcelDTO);
            }

        }


        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("统计表格", "UTF-8");
        response.setHeader("Content-disposition", "attachment;fileName=" + fileName + ".xlsx");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet writeSheet1 = EasyExcel.writerSheet(0, "今日记录").head(CourierInfoExcelDTO.class).build();
        WriteSheet writeSheet2 = EasyExcel.writerSheet(1, "统计").head(head(String.valueOf(courierInfoList.size()))).registerWriteHandler(new ExcelWidthStyleStrategy()).build();
        excelWriter.write(courierInfoList, writeSheet1);
        excelWriter.write(courierSiteExcelDTOList, writeSheet2);
        excelWriter.finish();


    }

    @Override
    public QueryStatisticsVO statisticsReconciliation(StatisticsQueryDTO statisticsQueryDTO) {
        CourierSite courierSite = courierSiteService.getById(statisticsQueryDTO.getSiteId());
        if (courierSite.getParentId() == 0 && StringUtils.isBlank(statisticsQueryDTO.getCourierCode())
                && StringUtils.isBlank(statisticsQueryDTO.getCourierName()) && StringUtils.isBlank(statisticsQueryDTO.getUserName())
                && StringUtils.isBlank(statisticsQueryDTO.getUserPhone()) && Objects.isNull(statisticsQueryDTO.getCourierStatus())) {
            return getParentQueryStatisticsVO(statisticsQueryDTO);
        } else {
            return getChildQueryStatisticsVO(statisticsQueryDTO);
        }
    }

    @Override
    public void statisticsExcel(StatisticsQueryDTO statisticsQueryDTO, HttpServletResponse response) throws Exception {
        List<CourierSite> courierSiteList = courierSiteService.list();
        Map<Integer, CourierSite> map = courierSiteList.stream().collect(Collectors.toMap(CourierSite::getId, a -> a, (k1, k2) -> k1));
        CourierSite courierSite = map.get(statisticsQueryDTO.getSiteId());
        List list = Lists.newArrayList();
        List<QueryStatisticsVO> queryStatisticsVOList = Lists.newArrayList();
        QueryStatisticsVO queryStatisticsVO = new QueryStatisticsVO();
        queryStatisticsVOList.add(queryStatisticsVO);
        Long startTime = DateUtil.stringDate2Timespan(statisticsQueryDTO.getStartTime(), DateUtil.DATE_FORMAT_YYYY_MM_DD_HH_MM_SS);
        Long endTime = DateUtil.stringDate2Timespan(statisticsQueryDTO.getEndTime(), DateUtil.DATE_FORMAT_YYYY_MM_DD_HH_MM_SS);
        if (courierSite.getParentId() == 0 && StringUtils.isBlank(statisticsQueryDTO.getCourierCode())
                && StringUtils.isBlank(statisticsQueryDTO.getCourierName()) && StringUtils.isBlank(statisticsQueryDTO.getUserName())
                && StringUtils.isBlank(statisticsQueryDTO.getUserPhone()) && Objects.isNull(statisticsQueryDTO.getCourierStatus())) {


            LambdaQueryWrapper<CourierInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.gt(StringUtils.isNotBlank(statisticsQueryDTO.getStartTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getStartTime())
                    .lt(StringUtils.isNotBlank(statisticsQueryDTO.getEndTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getEndTime())
                    .eq(CourierInfo::getSiteId, statisticsQueryDTO.getSiteId());


            List<CourierInfo> courierInfoLDtoist = list(wrapper);


            Map<Integer, List<CourierInfo>> courierInfoMap = new HashMap<>();
            if (CollectionUtil.isNotEmpty(courierInfoLDtoist)) {
                courierInfoMap = courierInfoLDtoist.stream()
                        .collect(Collectors.groupingBy(CourierInfo::getCourierStatus));
            }


            List<CourierInfo> storageList = courierInfoLDtoist.stream()
                    //根据两个属性进行过滤
                    .filter(s -> s.getCreateTime().getTime() > startTime && s.getCreateTime().getTime() < endTime)
                    .collect(Collectors.toList());
            queryStatisticsVO.setStorageCount(CollectionUtil.isNotEmpty(storageList) ? storageList.size() : 0);
            List<CourierInfo> deliveryList = courierInfoMap.get(CourierStatusEnum.DELIVERY.getCode());
            queryStatisticsVO.setDeliveryCount(CollectionUtil.isNotEmpty(deliveryList) ? deliveryList.size() : 0);

            List<CourierInfo> returnStorageList = courierInfoMap.get(CourierStatusEnum.RETURN_STORAGE.getCode());
            List<CourierInfo> returnDeliveryList = courierInfoMap.get(CourierStatusEnum.RETURN_DELIVERY.getCode());
            int aberrantCount = (CollectionUtil.isNotEmpty(returnStorageList) ? returnStorageList.size() : 0) + (CollectionUtil.isNotEmpty(returnDeliveryList) ? returnDeliveryList.size() : 0);
            queryStatisticsVO.setAberrantCount(aberrantCount);
            queryStatisticsVO.setTotal(storageList.size() - aberrantCount);

//            BigDecimal total = new BigDecimal(String.valueOf(storageList.size()-aberrantCount));
//            BigDecimal unit = new BigDecimal("0.3");
//            BigDecimal result = total.multiply(unit);
//            queryStatisticsVO.setIncome(result.toString());


            List<Integer> siteIdList = Lists.newArrayList();
            if (CollectionUtil.isEmpty(statisticsQueryDTO.getSiteIdList())) {
                List<ParentStatisticsVO> parentStatisticsVOList = getExcelParentQueryStatisticsVO(statisticsQueryDTO);
                if (CollectionUtil.isNotEmpty(parentStatisticsVOList)) {
                    siteIdList = parentStatisticsVOList.stream().map(ParentStatisticsVO::getSiteId).
                            collect(Collectors.toList());
                }
            } else {
                siteIdList = statisticsQueryDTO.getSiteIdList();
            }


            if (CollectionUtil.isNotEmpty(siteIdList)) {
                BigDecimal totalAmount = new BigDecimal(0);
                for (Integer siteId : siteIdList) {
                    CourierSite childCourierSite = courierSiteMapper.selectById(siteId);
                    LambdaQueryWrapper<CourierInfo> courierQueryWrapper = new LambdaQueryWrapper<>();
                    courierQueryWrapper.gt(StringUtils.isNotBlank(statisticsQueryDTO.getStartTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getStartTime())
                            .lt(StringUtils.isNotBlank(statisticsQueryDTO.getEndTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getEndTime())
                            .eq(CourierInfo::getSiteId, courierSite.getId())
                            .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
                    List<CourierInfo> courierInfos = list(courierQueryWrapper);
                    BigDecimal childTotal = new BigDecimal(String.valueOf(courierInfos.size()));
                    BigDecimal childUnit = new BigDecimal(childCourierSite.getFee());
                    BigDecimal childResult = childTotal.multiply(childUnit);
                    totalAmount = totalAmount.add(childResult);
                }
                queryStatisticsVO.setIncome(totalAmount.toString());
                LambdaQueryWrapper<CourierInfo> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.in(CourierInfo::getSiteId, siteIdList);
                queryWrapper.eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
                List<CourierInfo> courierList = list(queryWrapper);
                if (CollectionUtil.isNotEmpty(courierList)) {
                    for (CourierInfo courierInfo : courierList) {
                        ChildStatisticsVO childStatisticsVO = new ChildStatisticsVO();
                        BeanUtils.copyProperties(courierInfo, childStatisticsVO);
                        childStatisticsVO.setSiteName(map.get(courierInfo.getSiteId()).getSiteName());
                        childStatisticsVO.setCourierStatusName(CourierStatusEnum.getValue(childStatisticsVO.getCourierStatus()));
                        list.add(childStatisticsVO);
                    }
                }

            }

        } else {

            List<Integer> siteIdList = Lists.newArrayList();

            CourierSite site = courierSiteService.getById(statisticsQueryDTO.getSiteId());
            if (site.getParentId() == 0) {
                LambdaQueryWrapper<CourierSite> siteQueryWrapper = new LambdaQueryWrapper<>();
                siteQueryWrapper.eq(CourierSite::getParentId, site.getId());
                List<CourierSite> courierSiteList1 = courierSiteService.list(siteQueryWrapper);
                siteIdList = courierSiteList1.stream().map(CourierSite::getId).collect(Collectors.toList());


            }

            LambdaQueryWrapper<CourierInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper
                    .gt(StringUtils.isNotBlank(statisticsQueryDTO.getStartTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getStartTime())
                    .lt(StringUtils.isNotBlank(statisticsQueryDTO.getEndTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getEndTime())
                    .eq(CourierInfo::getSiteId, statisticsQueryDTO.getSiteId())
                    .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());


            List<CourierInfo> childList = list(queryWrapper);

            Map<Integer, List<CourierInfo>> courierInfoMap = childList.stream()
                    .collect(Collectors.groupingBy(CourierInfo::getCourierStatus));


            List<CourierInfo> storageList = childList.stream()
                    //根据两个属性进行过滤
                    .filter(s -> s.getCreateTime().getTime() > startTime && s.getCreateTime().getTime() < endTime)
                    .collect(Collectors.toList());
            queryStatisticsVO.setStorageCount(CollectionUtil.isNotEmpty(storageList) ? storageList.size() : 0);
            List<CourierInfo> deliveryList = courierInfoMap.get(CourierStatusEnum.DELIVERY.getCode());
            queryStatisticsVO.setDeliveryCount(CollectionUtil.isNotEmpty(deliveryList) ? deliveryList.size() : 0);


            List<CourierInfo> returnList = courierInfoMap.get(CourierStatusEnum.RETURN_STORAGE.getCode());
            List<CourierInfo> returnDeliveryList = courierInfoMap.get(CourierStatusEnum.RETURN_DELIVERY.getCode());

            int aberrantCount = (CollectionUtil.isNotEmpty(returnList) ? returnList.size() : 0) + (CollectionUtil.isNotEmpty(returnDeliveryList) ? returnDeliveryList.size() : 0);
            queryStatisticsVO.setAberrantCount(aberrantCount);
            queryStatisticsVO.setTotal(storageList.size() - aberrantCount);

            BigDecimal total = new BigDecimal(String.valueOf(storageList.size() - aberrantCount));
//            BigDecimal unit = new BigDecimal("0.1");
            BigDecimal unit = new BigDecimal(site.getFee());
            BigDecimal result = total.multiply(unit);
            queryStatisticsVO.setIncome(result.toString());


            List<Integer> courierIdList = Lists.newArrayList();
            if (CollectionUtil.isEmpty(statisticsQueryDTO.getCourierIdList())) {
                List<ChildStatisticsVO> childStatisticsVOList = getExcelChildQueryStatisticsVO(statisticsQueryDTO, siteIdList, site);
                if (CollectionUtil.isNotEmpty(childStatisticsVOList)) {
                    courierIdList = childStatisticsVOList.stream().map(ChildStatisticsVO::getId).
                            collect(Collectors.toList());
                }
            } else {
                courierIdList = statisticsQueryDTO.getCourierIdList();
            }

            LambdaQueryWrapper<CourierInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(CourierInfo::getId, courierIdList);
            wrapper.eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
            List<CourierInfo> courierInfoList = list(wrapper);
            if (CollectionUtil.isNotEmpty(courierInfoList)) {
                for (CourierInfo courierInfo : courierInfoList) {
                    ChildStatisticsVO childStatisticsVO = new ChildStatisticsVO();
                    if (Objects.nonNull(courierInfo.getNextSiteId())) {
                        courierSite = courierSiteService.getById(courierInfo.getNextSiteId());
                        childStatisticsVO.setType(1);
                    } else {
                        courierSite = courierSiteService.getById(courierInfo.getSiteId());
                        childStatisticsVO.setType(2);
                    }

                    BeanUtils.copyProperties(courierInfo, childStatisticsVO);
                    childStatisticsVO.setSiteName(Objects.nonNull(courierSite) ? courierSite.getSiteName() : null);
                    childStatisticsVO.setSiteName(map.get(courierInfo.getSiteId()).getSiteName());
                    childStatisticsVO.setCourierStatusName(CourierStatusEnum.getValue(childStatisticsVO.getCourierStatus()));
                    list.add(childStatisticsVO);
                }
            }
        }
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("统计表格", "UTF-8");
        response.setHeader("Content-disposition", "attachment;fileName=" + fileName + ".xlsx");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet writeSheet1 = EasyExcel.writerSheet(1, "统计").head(QueryStatisticsVO.class).registerWriteHandler(new ExcelWidthStyleStrategy()).build();
        WriteSheet writeSheet2 = EasyExcel.writerSheet(0, "快递统计").head(ChildStatisticsVO.class).build();
        excelWriter.write(queryStatisticsVOList, writeSheet1);
        excelWriter.write(list, writeSheet2);
        excelWriter.finish();

    }

    @Override
    public Boolean storageStatus(String code) {
        LambdaQueryWrapper<CourierInfo> qeryWrapper = new LambdaQueryWrapper<>();
        qeryWrapper.eq(CourierInfo::getCourierCode, code);
        qeryWrapper.eq(CourierInfo::getSiteId, UserInfoUtil.getSiteId());
        qeryWrapper.eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());

        CourierInfo courierInfo = getOne(qeryWrapper);

        return Objects.nonNull(courierInfo);

    }

    @Override
    public DeliveryInfoVO info(String courierCode) throws Exception {
        log.error("info courierCode = {} ", courierCode);
        DeliveryInfoVO deliveryInfoVO = new DeliveryInfoVO();
        LambdaQueryWrapper<CourierInfo> qeryWrapper = new LambdaQueryWrapper<>();
        qeryWrapper.eq(CourierInfo::getCourierCode, courierCode);
        qeryWrapper.isNull(CourierInfo::getNextSiteId);
        qeryWrapper.eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
        CourierInfo courierInfo = getOne(qeryWrapper);
        if (Objects.isNull(courierInfo)) {
            log.error("info courierCode = {} 该快件不存在", courierCode);
            throw new BusinessException("该快件不存在");
        }
        deliveryInfoVO.setCourierName(courierInfo.getCourierName());
        deliveryInfoVO.setUserName(courierInfo.getUserName());
        deliveryInfoVO.setCourierCode(courierInfo.getCourierCode());
        deliveryInfoVO.setId(courierInfo.getId());
        CourierSite courierSite = courierSiteService.getById(courierInfo.getSiteId());
        if (Objects.nonNull(courierSite)) {
            deliveryInfoVO.setSiteName(courierSite.getSiteName());
            deliveryInfoVO.setSiteAddress(courierSite.getSiteAddress());
            deliveryInfoVO.setPhone(courierSite.getPhone());
        }
        return deliveryInfoVO;
    }


    @Override
    public List<ScanInfoVO> infoWxs(String courierCode,String userName,String password) throws Exception {
        log.error("scanInfo courierCode = {} ", courierCode);
        //UserInfo userInfo = userInfoService.getById(UserInfoUtil.getUserid());//从token中获取用户ID，再获取用户信息。不用账号密码参数
        UserInfo userInfo = userInfoService.findByUsernameToPassword(userName, password);//接口中带有用户账号和密码用于获取用户信息
        CourierSite couSite = courierSiteService.getById(userInfo.getSiteId());
        List<CourierInfo> listScanInfo;
        List<CourierSite> listCouSite = new ArrayList<>();
        if (couSite.getParentId() == 0) {
            listCouSite = getCouSite(userInfo.getSiteId());
            List<Integer> collect = listCouSite.stream()
                    .map(CourierSite::getId)
                    .collect(Collectors.toList());

            listScanInfo = getCourierInfo(courierCode, userInfo.getSiteId(),userInfo.getSiteId(),collect);
            collect = null;
        } else {
            listScanInfo = getCourierInfo(courierCode, userInfo.getSiteId(),null,null);
        }
        if (listScanInfo == null) {
            log.error("info courierCode = {} 该快件不存在", courierCode);
            throw new BusinessException("The courier does not exist");
        }
        List<ScanInfoVO> scanInfoVOList = new ArrayList<>();
        if (listScanInfo != null && listScanInfo.size() > 0){
            List<String> collect = listScanInfo.stream()
                    .map(CourierInfo::getCourierCode)
                    .collect(Collectors.toList());

            LambdaQueryWrapper<CourierDeliveryImageInfo> imageQueryWrapper = new LambdaQueryWrapper<>();
            imageQueryWrapper.in(CourierDeliveryImageInfo::getCourierCode, collect);
            imageQueryWrapper.eq(CourierDeliveryImageInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
            List<CourierDeliveryImageInfo> imageInfos = courierDeliveryImageService.list(imageQueryWrapper);// 预加载courierDeliveryImageInfo，避免N+1查询问题
            for (CourierInfo courierInfo:listScanInfo) {
                ScanInfoVO scanInfoVO = new ScanInfoVO();
                scanInfoVO.setStatus(courierInfo.getCourierStatus());
                scanInfoVO.setStorageTime(courierInfo.getStorageTime());
                scanInfoVO.setDeliveryTime(courierInfo.getDeliveryTime());
                BeanUtils.copyProperties(courierInfo, scanInfoVO);
                CourierDeliveryImageInfo imageInfo = imageInfos.stream()
                        .filter(i -> i.getCourierCode().equals(courierInfo.getCourierCode()) &&
                                i.getDeleteStatus().equals(DeleteStatusEnum.NOT_DELETED.getCode()))
                        .findFirst()
                        .orElse(null);
                if (imageInfo != null) {
                    scanInfoVO.setImageUrl(imageInfo.getImageUrl());
                    scanInfoVO.setStatus(2);
                }
                if (couSite.getParentId() == 0){
                    scanInfoVO.setNextSiteId(courierInfo.getSiteId());
                    CourierSite courierSite = listCouSite.stream()
                            .filter(t -> t.getId().equals(courierInfo.getSiteId()))
                            .findFirst()
                            .orElse(null);
                    scanInfoVO.setSiteName(courierSite.getSiteName());
                }else{
                    scanInfoVO.setNextSiteId(courierInfo.getSiteId());
                    scanInfoVO.setSiteName(couSite.getSiteName());
                }
                //scanInfoVO.setSiteName(couSite.getSiteName());
                scanInfoVOList.add(scanInfoVO);
            }
            collect = null;
        }
        return scanInfoVOList;
    }
    private List<CourierSite> getCouSite(Integer siteId){
        LambdaQueryWrapper<CourierSite> siteWrapper = new LambdaQueryWrapper<>();
        siteWrapper.eq(CourierSite::getParentId,siteId);
        siteWrapper.eq(CourierSite::getDeleteStatus,DeleteStatusEnum.NOT_DELETED.getCode());
        return courierSiteService.list(siteWrapper);
    }
    private List<CourierInfo> getCourierInfo(String courierCode, Integer siteId,Integer nextSiteId,List<Integer> collect) {
        LambdaQueryWrapper<CourierInfo> qeryWrapper = new LambdaQueryWrapper<>();
        qeryWrapper.like(CourierInfo::getCourierCode, courierCode);
        if (nextSiteId != null) {
            /*qeryWrapper.eq(CourierInfo::getSiteId, siteId);
            qeryWrapper.isNotNull(CourierInfo::getNextSiteId);*/

            qeryWrapper.in(CourierInfo::getSiteId,collect);
            //qeryWrapper.isNull(CourierInfo::getNextSiteId);
            qeryWrapper.orderByDesc(CourierInfo::getSiteId);
        } else {
            qeryWrapper.eq(CourierInfo::getSiteId, siteId);
            qeryWrapper.isNull(CourierInfo::getNextSiteId);
        }
        qeryWrapper.eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
        return list(qeryWrapper);
    }
    @Override
    public Page<CourierInfo> abnormalList(StatisticsQueryDTO statisticsQueryDTO) {
        LambdaQueryWrapper<CourierInfo> queryWrapper = new LambdaQueryWrapper<>();
        List<Integer> courierStatusList = Lists.newArrayList();
        courierStatusList.add(CourierStatusEnum.RETURN_STORAGE.getCode());
        courierStatusList.add(CourierStatusEnum.RETURN_DELIVERY.getCode());
        queryWrapper
                .gt(StringUtils.isNotBlank(statisticsQueryDTO.getStartTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getStartTime())
                .lt(StringUtils.isNotBlank(statisticsQueryDTO.getEndTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getEndTime())
                .eq(CourierInfo::getSiteId, statisticsQueryDTO.getSiteId())
                .in(CourierInfo::getCourierStatus, courierStatusList)
                .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());


        Page<CourierInfo> page = new Page<>();
        page.setCurrent(statisticsQueryDTO.getCurrent());
        page.setSize(statisticsQueryDTO.getSize());
        Page<CourierInfo> pageList = page(page, queryWrapper);
        return pageList;

    }

    @Override
    public void abnormalExcel(StatisticsQueryDTO statisticsQueryDTO, HttpServletResponse response) throws Exception {
        LambdaQueryWrapper<CourierInfo> queryWrapper = new LambdaQueryWrapper<>();
        List<Integer> courierStatusList = Lists.newArrayList();
        courierStatusList.add(CourierStatusEnum.RETURN_STORAGE.getCode());
        courierStatusList.add(CourierStatusEnum.RETURN_DELIVERY.getCode());
        if (CollectionUtil.isEmpty(statisticsQueryDTO.getCourierIdList())) {

            queryWrapper
                    .gt(StringUtils.isNotBlank(statisticsQueryDTO.getStartTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getStartTime())
                    .lt(StringUtils.isNotBlank(statisticsQueryDTO.getEndTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getEndTime())
                    .eq(CourierInfo::getSiteId, statisticsQueryDTO.getSiteId())
                    .in(CourierInfo::getCourierStatus, courierStatusList)
                    .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
        } else {
            queryWrapper
                    .eq(CourierInfo::getSiteId, statisticsQueryDTO.getSiteId())
                    .in(CourierInfo::getCourierStatus, courierStatusList)
                    .in(CourierInfo::getId, statisticsQueryDTO.getCourierIdList());

        }

        List<CourierInfo> pageList = list(queryWrapper);
        List<ChildStatisticsVO> list = Lists.newArrayList();
        if (CollectionUtil.isNotEmpty(pageList)) {
            for (CourierInfo courierInfo : pageList) {
                ChildStatisticsVO childStatisticsVO = new ChildStatisticsVO();
                BeanUtils.copyProperties(courierInfo, childStatisticsVO);
                list.add(childStatisticsVO);
            }

        }

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("快递明细", "UTF-8");
        response.setHeader("Content-disposition", "attachment;fileName=" + fileName + ".xlsx");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet writeSheet2 = EasyExcel.writerSheet(0, "快递统计").head(ChildStatisticsVO.class).build();
        excelWriter.write(list, writeSheet2);
        excelWriter.finish();


    }


    @Override
    public Page<CourierInfoDetailVO> myList(QueryCourierListDTO queryCourierListDTO) throws Exception {

        if (StringUtils.isBlank(queryCourierListDTO.getPhone())) {
            throw new RuntimeException("手机号不能为空");
        }
        LambdaQueryWrapper<CourierInfo> queryWrapper = new LambdaQueryWrapper<>();
        if (Objects.isNull(queryCourierListDTO.getCourierDeliveryStatus())) {
            List<Integer> courierStatusList = Lists.newArrayList();
            courierStatusList.add(CourierStatusEnum.STORAGE.getCode());
            queryWrapper
                    .and(wrapper -> wrapper
                            .eq(CourierInfo::getCourierStatus, CourierStatusEnum.STORAGE.getCode())
                            .isNotNull(CourierInfo::getNextSiteId))
                    .like(CourierInfo::getCourierCode, queryCourierListDTO.getKeyword())
                    .or(wrapper -> wrapper
                            .isNull(CourierInfo::getNextSiteId)
                            .like(CourierInfo::getCourierCode, queryCourierListDTO.getKeyword())
                    );
            queryWrapper.orderByDesc(CourierInfo::getUpdateTime);
        } else {
            if (queryCourierListDTO.getCourierDeliveryStatus() == 0) {
                List<Integer> courierStatusList = Lists.newArrayList();
                courierStatusList.add(CourierStatusEnum.HAVE_RECEIVED.getCode());
                courierStatusList.add(CourierStatusEnum.STORAGE.getCode());
                queryWrapper
                        .and(wrapper -> wrapper
                                .eq(CourierInfo::getUserPhone, queryCourierListDTO.getPhone())
                                .eq(CourierInfo::getCourierStatus, CourierStatusEnum.STORAGE.getCode())
                                .isNotNull(CourierInfo::getNextSiteId))
                        .or(wrapper -> wrapper
                                .eq(CourierInfo::getUserPhone, queryCourierListDTO.getPhone())
                                .in(CourierInfo::getCourierStatus, courierStatusList)
                                .isNull(CourierInfo::getNextSiteId)
                        )
                        .orderByDesc(CourierInfo::getUpdateTime);
            }
            if (queryCourierListDTO.getCourierDeliveryStatus() == 1) {
                queryWrapper
                        .eq(CourierInfo::getUserPhone, queryCourierListDTO.getPhone())
                        .eq(CourierInfo::getCourierStatus, CourierStatusEnum.STORAGE.getCode())
                        .isNotNull(CourierInfo::getNextSiteId)
                        .orderByDesc(CourierInfo::getUpdateTime);
            }
            if (queryCourierListDTO.getCourierDeliveryStatus() == 2) {
                queryWrapper
                        .eq(CourierInfo::getUserPhone, queryCourierListDTO.getPhone())
                        .eq(CourierInfo::getCourierStatus, CourierStatusEnum.STORAGE.getCode())
                        .isNull(CourierInfo::getNextSiteId)
                        .orderByDesc(CourierInfo::getUpdateTime);
            }
            if (queryCourierListDTO.getCourierDeliveryStatus() == 3) {
                queryWrapper
                        .eq(CourierInfo::getUserPhone, queryCourierListDTO.getPhone())
                        .eq(CourierInfo::getCourierStatus, CourierStatusEnum.HAVE_RECEIVED.getCode())
                        .isNull(CourierInfo::getNextSiteId)
                        .orderByDesc(CourierInfo::getUpdateTime);
            }
        }

        Page<CourierInfo> page = new Page<>();
        page.setCurrent(queryCourierListDTO.getCurrent());
        page.setSize(queryCourierListDTO.getSize());
        Page pageList = page(page, queryWrapper);

        List<CourierInfo> records = pageList.getRecords();

        List<CourierInfoDetailVO> courierInfoDetailVOList = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(records)) {
            for (CourierInfo courierInfo : records) {
                CourierSite courierSite = new CourierSite();

                if (Objects.nonNull(courierInfo.getNextSiteId())) {
                    courierSite = courierSiteService.getById(courierInfo.getNextSiteId());
                } else {
                    courierSite = courierSiteService.getById(courierInfo.getSiteId());
                }

                CourierInfoDetailVO courierInfoDetailVO = new CourierInfoDetailVO();

                Date date = new Date();
                String today = DateUtil.DateToString(date, DateUtil.DATE_FORMAT_YYYY_MM_DD);
                String storageTime = DateUtil.DateToString(courierInfo.getStorageTime(), DateUtil.DATE_FORMAT_YYYY_MM_DD);
                long storageDays = DateUtil.getDaySub(storageTime, today);
                BeanUtils.copyProperties(courierInfo, courierInfoDetailVO);
                //设置配送状态
                if (courierInfo.getNextSiteId() == null) {
                    if (courierInfo.getCourierStatus().equals(CourierStatusEnum.STORAGE.getCode())) {
                        courierInfoDetailVO.setCourierDeliveryStatus(2);
                    } else {
                        courierInfoDetailVO.setCourierDeliveryStatus(3);
                    }

                } else {
                    courierInfoDetailVO.setCourierDeliveryStatus(1);
                }
                courierInfoDetailVO.setSitePhone(courierSite.getPhone());
                courierInfoDetailVO.setSiteName(courierSite.getSiteName());
                courierInfoDetailVO.setStorageDays(storageDays);
                courierInfoDetailVO.setMessageAdviceStatus(courierInfo.getAdviceStatus());
                //获取客服电话
                int parentId = courierSite.getParentId();
                courierInfoDetailVO.setParentSiteId(parentId);
                if (parentId > 0) {
                    CourierSite courierParentSite = courierSiteService.getById(parentId);
                    if (courierSite != null) {
                        String n1 = courierParentSite.getCustomerServicePhoneName1();
                        String p1 = courierParentSite.getCustomerServicePhoneNum1();
                        String n2 = courierParentSite.getCustomerServicePhoneName2();
                        String p2 = courierParentSite.getCustomerServicePhoneNum2();
                        String n3 = courierParentSite.getCustomerServicePhoneName3();
                        String p3 = courierParentSite.getCustomerServicePhoneNum3();
                        List<ServicePhoneVO> servicePhoneList = new ArrayList<>();
                        if (!TextUtils.isEmpty(n1) && !TextUtils.isEmpty(p1)) {
                            ServicePhoneVO servicePhoneVO1 = new ServicePhoneVO();
                            servicePhoneVO1.setName(n1);
                            servicePhoneVO1.setPhone(p1);
                            servicePhoneList.add(servicePhoneVO1);
                        }
                        if (!TextUtils.isEmpty(n2) && !TextUtils.isEmpty(p2)) {
                            ServicePhoneVO servicePhoneVO2 = new ServicePhoneVO();
                            servicePhoneVO2.setName(n2);
                            servicePhoneVO2.setPhone(p2);
                            servicePhoneList.add(servicePhoneVO2);
                        }
                        if (!TextUtils.isEmpty(n3) && !TextUtils.isEmpty(p3)) {
                            ServicePhoneVO servicePhoneVO3 = new ServicePhoneVO();
                            servicePhoneVO3.setName(n3);
                            servicePhoneVO3.setPhone(p3);
                            servicePhoneList.add(servicePhoneVO3);
                        }
                        courierInfoDetailVO.setServicePhoneList(servicePhoneList);
                    }
                }
                courierInfoDetailVOList.add(courierInfoDetailVO);
            }

        }

        return pageList.setRecords(courierInfoDetailVOList);
    }

    @Override
    public Integer myNum(QueryCourierListDTO queryCourierListDTO) {
        if (StringUtils.isBlank(queryCourierListDTO.getPhone())) {
            throw new RuntimeException("手机号不能为空");
        }
        LambdaQueryWrapper<CourierInfo> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper
                .and(wrapper -> wrapper
                        .eq(CourierInfo::getUserPhone, queryCourierListDTO.getPhone())
                        .eq(CourierInfo::getCourierStatus, CourierStatusEnum.STORAGE.getCode())
                        .isNotNull(CourierInfo::getNextSiteId))
                .or(wrapper -> wrapper
                        .eq(CourierInfo::getUserPhone, queryCourierListDTO.getPhone())
                        .eq(CourierInfo::getCourierStatus, CourierStatusEnum.STORAGE.getCode())
                        .isNull(CourierInfo::getNextSiteId)
                )
                .orderByDesc(CourierInfo::getUpdateTime);
        int count = count(queryWrapper);
        return count;
    }

    @Override
    public ScanInfoVO scanInfo(String courierCode, Integer nextSiteId) throws Exception {
        log.error("scanInfo courierCode = {} ", courierCode);
        ScanInfoVO scanInfoVO = new ScanInfoVO();
        LambdaQueryWrapper<CourierInfo> qeryWrapper = new LambdaQueryWrapper<>();
        qeryWrapper.eq(CourierInfo::getCourierCode, courierCode);
        qeryWrapper.eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
        List<CourierInfo> courierInfoList = list(qeryWrapper);
        if (CollectionUtils.isEmpty(courierInfoList)) {
            log.error("scanInfo courierCode = {} 该快件不存在", courierCode);
            throw new BusinessException("该快件不存在");
        }
        scanInfoVO.setStatus(1);
        CourierSite courierSite = new CourierSite();
        for (CourierInfo e : courierInfoList) {
            if (e.getSiteId().equals(UserInfoUtil.getSiteId())) {
                scanInfoVO.setStatus(2);
            }
            if (Objects.nonNull(e.getNextSiteId())) {
                courierSite = courierSiteService.getById(e.getNextSiteId());
                scanInfoVO.setNextSiteId(e.getNextSiteId());
                if (Objects.nonNull(nextSiteId)) {
                    if (!e.getNextSiteId().equals(nextSiteId)) {
                        throw new BusinessException("快件错分，请妥善保管");
                    }
                } else {
                    if (!e.getNextSiteId().equals(UserInfoUtil.getSiteId())) {
                        throw new BusinessException("快件错分，请妥善保管");
                    }
                }

            }
        }
        BeanUtils.copyProperties(courierInfoList.get(0), scanInfoVO);
        scanInfoVO.setSiteName(courierSite.getSiteName());
        return scanInfoVO;
    }

    private QueryStatisticsVO getChildQueryStatisticsVO(StatisticsQueryDTO statisticsQueryDTO) {
        List<Integer> siteIdList = Lists.newArrayList();

        CourierSite site = courierSiteService.getById(statisticsQueryDTO.getSiteId());
        if (site.getParentId() == 0) {
            LambdaQueryWrapper<CourierSite> siteQueryWrapper = new LambdaQueryWrapper<>();
            siteQueryWrapper.eq(CourierSite::getParentId, site.getId());
            List<CourierSite> courierSiteList = courierSiteService.list(siteQueryWrapper);
            siteIdList = courierSiteList.stream().map(CourierSite::getId).collect(Collectors.toList());


        }

        QueryStatisticsVO queryStatisticsVO = new QueryStatisticsVO();

        LambdaQueryWrapper<CourierInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(CourierInfo::getSiteId, statisticsQueryDTO.getSiteId())
                .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());

        if (!TextUtils.isEmpty(statisticsQueryDTO.getEndTime())) {
            queryWrapper.lt(StringUtils.isNotBlank(statisticsQueryDTO.getEndTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getEndTime());
        }
        if (!TextUtils.isEmpty(statisticsQueryDTO.getStartTime())) {
            queryWrapper.gt(StringUtils.isNotBlank(statisticsQueryDTO.getStartTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getStartTime());
        }
        if (statisticsQueryDTO.getUserPhoneHide() != null) {
            if (statisticsQueryDTO.getUserPhoneHide() == 1) {
                queryWrapper.eq(CourierInfo::getUserPhoneHide, "0");
            } else if (statisticsQueryDTO.getUserPhoneHide() == 2) {
                queryWrapper.eq(CourierInfo::getUserPhoneHide, "1");
            }
        }
        List<CourierInfo> list = list(queryWrapper);

        Map<Integer, List<CourierInfo>> courierInfoMap = list.stream()
                .collect(Collectors.groupingBy(CourierInfo::getCourierStatus));


        List<CourierInfo> storageList = list.stream()
                .collect(Collectors.toList());
        if (!TextUtils.isEmpty(statisticsQueryDTO.getStartTime()) && !TextUtils.isEmpty(statisticsQueryDTO.getEndTime())) {
            Long startTime = DateUtil.stringDate2Timespan(statisticsQueryDTO.getStartTime(), DateUtil.DATE_FORMAT_YYYY_MM_DD_HH_MM_SS);
            Long endTime = DateUtil.stringDate2Timespan(statisticsQueryDTO.getEndTime(), DateUtil.DATE_FORMAT_YYYY_MM_DD_HH_MM_SS);
            storageList = list.stream()
                    //根据两个属性进行过滤
                    .filter(s -> s.getCreateTime().getTime() > startTime && s.getCreateTime().getTime() < endTime)
                    .collect(Collectors.toList());
        }

        queryStatisticsVO.setStorageCount(CollectionUtil.isNotEmpty(storageList) ? storageList.size() : 0);
        List<CourierInfo> deliveryList = courierInfoMap.get(CourierStatusEnum.HAVE_RECEIVED.getCode());
        queryStatisticsVO.setDeliveryCount(CollectionUtil.isNotEmpty(deliveryList) ? deliveryList.size() : 0);


        List<CourierInfo> returnList = courierInfoMap.get(CourierStatusEnum.RETURN_STORAGE.getCode());
        List<CourierInfo> returnDeliveryList = courierInfoMap.get(CourierStatusEnum.RETURN_DELIVERY.getCode());

        int aberrantCount = (CollectionUtil.isNotEmpty(returnList) ? returnList.size() : 0) + (CollectionUtil.isNotEmpty(returnDeliveryList) ? returnDeliveryList.size() : 0);
        queryStatisticsVO.setAberrantCount(aberrantCount);
        queryStatisticsVO.setTotal(storageList.size() - aberrantCount);

        BigDecimal total = new BigDecimal(String.valueOf(storageList.size() - aberrantCount));
//        BigDecimal unit = new BigDecimal("0.1");
        BigDecimal unit = new BigDecimal(site.getFee());
        BigDecimal result = total.multiply(unit);
        queryStatisticsVO.setIncome(result.toString());


        Page page = new Page<>();
        page.setSize(statisticsQueryDTO.getSize());
        page.setCurrent(statisticsQueryDTO.getCurrent());
        LambdaQueryWrapper<CourierInfo> courierInfoQueryWrapper = new LambdaQueryWrapper<>();
        List<Integer> finalSiteIdList = siteIdList;
        courierInfoQueryWrapper.like(StringUtils.isNotBlank(statisticsQueryDTO.getCourierCode()), CourierInfo::getCourierCode, statisticsQueryDTO.getCourierCode())
                .eq(StringUtils.isNotBlank(statisticsQueryDTO.getCourierName()), CourierInfo::getCourierName, statisticsQueryDTO.getCourierName())
                .like(StringUtils.isNotBlank(statisticsQueryDTO.getUserName()), CourierInfo::getUserName, statisticsQueryDTO.getUserName())
                .like(StringUtils.isNotBlank(statisticsQueryDTO.getUserPhone()), CourierInfo::getUserPhone, statisticsQueryDTO.getUserPhone())
                .eq(Objects.nonNull(statisticsQueryDTO.getCourierStatus()), CourierInfo::getCourierStatus, statisticsQueryDTO.getCourierStatus())
                .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode())
                .orderByDesc(CourierInfo::getStorageTime);

        if (!TextUtils.isEmpty(statisticsQueryDTO.getStartTime())) {
            courierInfoQueryWrapper.gt(StringUtils.isNotBlank(statisticsQueryDTO.getStartTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getStartTime());
        }
        if (!TextUtils.isEmpty(statisticsQueryDTO.getEndTime())) {
            courierInfoQueryWrapper.lt(StringUtils.isNotBlank(statisticsQueryDTO.getEndTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getEndTime());
        }

        if (statisticsQueryDTO.getUserPhoneHide() != null) {
            if (statisticsQueryDTO.getUserPhoneHide() == 1) {
                courierInfoQueryWrapper.eq(CourierInfo::getUserPhoneHide, "0");
            } else if (statisticsQueryDTO.getUserPhoneHide() == 2) {
                courierInfoQueryWrapper.eq(CourierInfo::getUserPhoneHide, "1");
            }
        }

        if (site.getParentId() == 0) {
            courierInfoQueryWrapper.and(wr -> wr
                    .and(wrapper -> wrapper
                            .eq(CourierInfo::getSiteId, statisticsQueryDTO.getSiteId())
                            .eq(CourierInfo::getCourierStatus, CourierStatusEnum.STORAGE.getCode()))
                    .or(wrapper -> wrapper
                            .in(!CollectionUtils.isEmpty(finalSiteIdList), CourierInfo::getSiteId, finalSiteIdList)

                    ));

        } else {
            courierInfoQueryWrapper.and(wr -> wr
                    .and(wrapper -> wrapper
                            .eq(CourierInfo::getNextSiteId, statisticsQueryDTO.getSiteId())
                            .eq(CourierInfo::getCourierStatus, CourierStatusEnum.STORAGE.getCode()))
                    .or(wrapper -> wrapper
                            .eq(CourierInfo::getSiteId, statisticsQueryDTO.getSiteId())
                    ));
//            courierInfoQueryWrapper.eq(CourierInfo::getSiteId, statisticsQueryDTO.getSiteId());
        }
        Page pageList = page(page, courierInfoQueryWrapper);
        if (CollectionUtil.isEmpty(pageList.getRecords())) {
            queryStatisticsVO.setList(pageList);
            return queryStatisticsVO;
        }
        List<CourierInfo> records = pageList.getRecords();
        List<ChildStatisticsVO> childStatisticsVOList = Lists.newArrayList();
        //查找主账号信息
        LambdaQueryWrapper<CourierInfo> query = new LambdaQueryWrapper<>();
        query.like(StringUtils.isNotBlank(statisticsQueryDTO.getCourierCode()), CourierInfo::getCourierCode, statisticsQueryDTO.getCourierCode())
                .eq(StringUtils.isNotBlank(statisticsQueryDTO.getCourierName()), CourierInfo::getCourierName, statisticsQueryDTO.getCourierName())
                .like(StringUtils.isNotBlank(statisticsQueryDTO.getUserName()), CourierInfo::getUserName, statisticsQueryDTO.getUserName())
                .like(StringUtils.isNotBlank(statisticsQueryDTO.getUserPhone()), CourierInfo::getUserPhone, statisticsQueryDTO.getUserPhone())
                .eq(Objects.nonNull(statisticsQueryDTO.getCourierStatus()), CourierInfo::getCourierStatus, statisticsQueryDTO.getCourierStatus())
                .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
        if (!TextUtils.isEmpty(statisticsQueryDTO.getStartTime())) {
            query.gt(StringUtils.isNotBlank(statisticsQueryDTO.getStartTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getStartTime());
        }
        if (!TextUtils.isEmpty(statisticsQueryDTO.getEndTime())) {
            query.lt(StringUtils.isNotBlank(statisticsQueryDTO.getEndTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getEndTime());
        }
        query.isNotNull(CourierInfo::getNextSiteId);
        //耗时操作
//        List<CourierInfo> mainCourierInfo = list(query);
        Page<CourierInfo> courierInfoPage = page(page, query);
        List<CourierInfo> mainCourierInfo = courierInfoPage.getRecords();
        Map<String, Date> mainMap = new HashMap<>();
        for (CourierInfo courierInfo : mainCourierInfo) {
            if (!mainMap.containsKey(courierInfo.getCourierCode())) {
                mainMap.put(courierInfo.getCourierCode(), courierInfo.getStorageTime());
            }
        }
        CourierSite courierSite = new CourierSite();
        //耗时操作
        for (CourierInfo courierInfo : records) {
            ChildStatisticsVO childStatisticsVO = new ChildStatisticsVO();
            if (Objects.nonNull(courierInfo.getNextSiteId())) {
                courierSite = courierSiteService.getById(courierInfo.getNextSiteId());
                childStatisticsVO.setType(1);
                if (mainMap.containsKey(courierInfo.getCourierCode())) {
                    childStatisticsVO.setMainStorageTime(mainMap.get(courierInfo.getCourierCode()));
                }
            } else {
                courierSite = courierSiteService.getById(courierInfo.getSiteId());
                childStatisticsVO.setType(2);
                if (mainMap.containsKey(courierInfo.getCourierCode())) {
                    childStatisticsVO.setMainStorageTime(mainMap.get(courierInfo.getCourierCode()));
                }
                childStatisticsVO.setStorageTime(courierInfo.getStorageTime());
            }
            LambdaQueryWrapper<CourierDeliveryImageInfo> imageQueryWrapper = new LambdaQueryWrapper<>();
            imageQueryWrapper.eq(CourierDeliveryImageInfo::getCourierCode, courierInfo.getCourierCode());
            imageQueryWrapper.eq(CourierDeliveryImageInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
            CourierDeliveryImageInfo courierDeliveryImageInfo = courierDeliveryImageService.getOne(imageQueryWrapper);

            childStatisticsVO.setSiteName(Objects.nonNull(courierSite) ? courierSite.getSiteName() : null);
            childStatisticsVO.setId(courierInfo.getId());
            childStatisticsVO.setUserName(courierInfo.getUserName());
            childStatisticsVO.setUserPhone(courierInfo.getUserPhone());
            childStatisticsVO.setUserAddress(courierInfo.getUserAddress());
            childStatisticsVO.setCourierName(courierInfo.getCourierName());
            childStatisticsVO.setCourierCode(courierInfo.getCourierCode());
            childStatisticsVO.setDeliveryTime(courierInfo.getDeliveryTime());
            childStatisticsVO.setUserPhoneHide(courierInfo.getUserPhoneHide() == 0 ? 1 : 2);
//            childStatisticsVO.setImageUrl(courierInfo.getImageUrl());
            if (courierDeliveryImageInfo != null) {
                childStatisticsVO.setImageUrl(courierDeliveryImageInfo.getImageUrl());
                childStatisticsVO.setCourierStatus(CourierStatusEnum.HAVE_RECEIVED.getCode());
            } else {
                childStatisticsVO.setCourierStatus(courierInfo.getCourierStatus());
            }
            childStatisticsVO.setMainStorageImageUrl(courierInfo.getMainStorageImageUrl());
            childStatisticsVO.setStorageImageUrl(courierInfo.getStorageImageUrl());
            childStatisticsVO.setMessageAdviceStatus(courierInfo.getAdviceStatus());
            childStatisticsVOList.add(childStatisticsVO);
        }
        pageList.setRecords(childStatisticsVOList);
        queryStatisticsVO.setList(pageList);
        return queryStatisticsVO;
    }


    private List getExcelChildQueryStatisticsVO(StatisticsQueryDTO statisticsQueryDTO, List<Integer> siteIdList, CourierSite site) {

        LambdaQueryWrapper<CourierInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(statisticsQueryDTO.getCourierCode()), CourierInfo::getCourierCode, statisticsQueryDTO.getCourierCode())
                .like(StringUtils.isNotBlank(statisticsQueryDTO.getUserName()), CourierInfo::getUserName, statisticsQueryDTO.getUserName())
                .like(StringUtils.isNotBlank(statisticsQueryDTO.getUserPhone()), CourierInfo::getUserPhone, statisticsQueryDTO.getUserPhone())
                .gt(StringUtils.isNotBlank(statisticsQueryDTO.getStartTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getStartTime())
                .lt(StringUtils.isNotBlank(statisticsQueryDTO.getEndTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getEndTime())
                .eq(CourierInfo::getSiteId, statisticsQueryDTO.getSiteId())
                .eq(Objects.nonNull(statisticsQueryDTO.getCourierStatus()), CourierInfo::getCourierStatus, statisticsQueryDTO.getCourierStatus())
                .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());


        if (site.getParentId() == 0) {
            queryWrapper.and(wr -> wr
                    .and(wrapper -> wrapper
                            .eq(CourierInfo::getSiteId, statisticsQueryDTO.getSiteId())
                            .eq(CourierInfo::getCourierStatus, CourierStatusEnum.STORAGE.getCode()))
                    .or(wrapper -> wrapper
                            .in(!CollectionUtils.isEmpty(siteIdList), CourierInfo::getSiteId, siteIdList)

                    ));

        } else {
            queryWrapper.eq(CourierInfo::getSiteId, statisticsQueryDTO.getSiteId());
        }

        List<CourierInfo> pageList = list(queryWrapper);
        if (CollectionUtil.isEmpty(pageList)) {
            return pageList;
        }


        List<ChildStatisticsVO> childStatisticsVOList = Lists.newArrayList();

        for (CourierInfo courierInfo : pageList) {
            ChildStatisticsVO childStatisticsVO = new ChildStatisticsVO();
            CourierSite courierSite = courierSiteService.getById(courierInfo.getNextSiteId());
            childStatisticsVO.setChildSiteName(Objects.nonNull(courierSite) ? courierSite.getSiteName() : null);
            childStatisticsVO.setId(courierInfo.getId());
            childStatisticsVO.setUserName(courierInfo.getUserName());
            childStatisticsVO.setUserPhone(courierInfo.getUserPhone());
            childStatisticsVO.setUserAddress(courierInfo.getUserAddress());
            childStatisticsVO.setCourierName(courierInfo.getCourierName());
            childStatisticsVO.setCourierCode(courierInfo.getCourierCode());
            childStatisticsVO.setCourierStatus(courierInfo.getCourierStatus());
            childStatisticsVO.setStorageTime(courierInfo.getStorageTime());
            childStatisticsVO.setDeliveryTime(courierInfo.getDeliveryTime());
            childStatisticsVOList.add(childStatisticsVO);
        }

        return childStatisticsVOList;
    }


    private QueryStatisticsVO getParentQueryStatisticsVO(StatisticsQueryDTO statisticsQueryDTO) {
        if(TextUtils.isEmpty(statisticsQueryDTO.getStartTime())) {
            statisticsQueryDTO.setStartTime("2023-7-23 00:00:11");
        }

        Page page = new Page<>();
        page.setSize(statisticsQueryDTO.getSize());
        page.setCurrent(statisticsQueryDTO.getCurrent());


        QueryStatisticsVO queryStatisticsVO = new QueryStatisticsVO();

        LambdaQueryWrapper<CourierInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourierInfo::getSiteId, statisticsQueryDTO.getSiteId())
                .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());

        if (!TextUtils.isEmpty(statisticsQueryDTO.getEndTime())) {
            queryWrapper.lt(StringUtils.isNotBlank(statisticsQueryDTO.getEndTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getEndTime());
        }
        if (!TextUtils.isEmpty(statisticsQueryDTO.getStartTime())) {
            queryWrapper.gt(StringUtils.isNotBlank(statisticsQueryDTO.getStartTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getStartTime());
        }

        if (statisticsQueryDTO.getUserPhoneHide() != null) {
            if (statisticsQueryDTO.getUserPhoneHide() == 1) {
                queryWrapper.eq(CourierInfo::getUserPhoneHide, 0);
            } else if (statisticsQueryDTO.getUserPhoneHide() == 2) {
                queryWrapper.eq(CourierInfo::getUserPhoneHide, 1);
            }
        }

        List<CourierInfo> list = list(queryWrapper);

        Map<Integer, List<CourierInfo>> courierInfoMap = list.stream()
                .collect(Collectors.groupingBy(CourierInfo::getCourierStatus));
        List<CourierInfo> storageList = list.stream()
                //根据两个属性进行过滤
                .collect(Collectors.toList());
        if (!TextUtils.isEmpty(statisticsQueryDTO.getStartTime()) && !TextUtils.isEmpty(statisticsQueryDTO.getEndTime())) {
            Long startTime = DateUtil.stringDate2Timespan(statisticsQueryDTO.getStartTime(), DateUtil.DATE_FORMAT_YYYY_MM_DD_HH_MM_SS);
            Long endTime = DateUtil.stringDate2Timespan(statisticsQueryDTO.getEndTime(), DateUtil.DATE_FORMAT_YYYY_MM_DD_HH_MM_SS);
            storageList = list.stream()
                    //根据两个属性进行过滤
                    .filter(s -> s.getCreateTime().getTime() > startTime && s.getCreateTime().getTime() < endTime)
                    .collect(Collectors.toList());
        }

        queryStatisticsVO.setStorageCount(CollectionUtil.isNotEmpty(storageList) ? storageList.size() : 0);
        List<CourierInfo> deliveryList = courierInfoMap.get(CourierStatusEnum.DELIVERY.getCode());
        queryStatisticsVO.setDeliveryCount(CollectionUtil.isNotEmpty(deliveryList) ? deliveryList.size() : 0);
        List<CourierInfo> returnStorageList = courierInfoMap.get(CourierStatusEnum.RETURN_STORAGE.getCode());
        List<CourierInfo> returnDeliveryList = courierInfoMap.get(CourierStatusEnum.RETURN_DELIVERY.getCode());
        int aberrantCount = (CollectionUtil.isNotEmpty(returnStorageList) ? returnStorageList.size() : 0) + (CollectionUtil.isNotEmpty(returnDeliveryList) ? returnDeliveryList.size() : 0);
        queryStatisticsVO.setAberrantCount(aberrantCount);
        queryStatisticsVO.setTotal(storageList.size() - aberrantCount);

//        BigDecimal total = new BigDecimal(String.valueOf(storageList.size()-aberrantCount));
//        BigDecimal unit = new BigDecimal("0.3");
//        BigDecimal result = total.multiply(unit);
//        queryStatisticsVO.setIncome(result.toString());

        BigDecimal totalAmount = new BigDecimal("0");


        LambdaQueryWrapper<CourierSite> siteQueryWrapper = new LambdaQueryWrapper<>();
        siteQueryWrapper.eq(CourierSite::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
        siteQueryWrapper.eq(CourierSite::getParentId, statisticsQueryDTO.getSiteId());
        Page pageList = courierSiteService.page(page, siteQueryWrapper);

        if (CollectionUtil.isEmpty(pageList.getRecords())) {
            queryStatisticsVO.setList(pageList);
            return queryStatisticsVO;
        }


        Map<Integer, List<CourierInfo>> siteMap = list.stream()
                .collect(Collectors.groupingBy(CourierInfo::getSiteId));

        List<ParentStatisticsVO> parentStatisticsVOList = Lists.newArrayList();
        List<CourierSite> records = pageList.getRecords();
        for (CourierSite courierSite : records) {

            LambdaQueryWrapper<CourierInfo> courierQueryWrapper = new LambdaQueryWrapper<>();
            courierQueryWrapper.gt(StringUtils.isNotBlank(statisticsQueryDTO.getStartTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getStartTime())
                    .lt(StringUtils.isNotBlank(statisticsQueryDTO.getEndTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getEndTime())
                    .eq(CourierInfo::getSiteId, courierSite.getId())
                    .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
            List<CourierInfo> courierInfos = list(courierQueryWrapper);

            LambdaQueryWrapper<CourierInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.gt(StringUtils.isNotBlank(statisticsQueryDTO.getStartTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getStartTime())
                    .lt(StringUtils.isNotBlank(statisticsQueryDTO.getEndTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getEndTime())
                    .eq(CourierInfo::getNextSiteId, courierSite.getId())
                    .eq(CourierInfo::getCourierStatus, CourierStatusEnum.STORAGE.getCode())
                    .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
            List<CourierInfo> pendingCourierInfoList = list(wrapper);

            if (CollectionUtil.isEmpty(courierInfos)) {
                courierInfos = Lists.newArrayList();
            }
            Map<Integer, List<CourierInfo>> map = courierInfos.stream()
                    .collect(Collectors.groupingBy(CourierInfo::getCourierStatus));
            ParentStatisticsVO parentStatisticsVO = new ParentStatisticsVO();
            parentStatisticsVO.setSiteId(courierSite.getId());
            parentStatisticsVO.setSiteName(courierSite.getSiteName());

            List<CourierInfo> returnStorages = map.get(CourierStatusEnum.RETURN_STORAGE.getCode());
            List<CourierInfo> returnDeliverys = map.get(CourierStatusEnum.RETURN_DELIVERY.getCode());
            int siteAberrantCount = (CollectionUtil.isNotEmpty(returnStorages) ? returnStorages.size() : 0) + (CollectionUtil.isNotEmpty(returnDeliverys) ? returnDeliverys.size() : 0);
            parentStatisticsVO.setAberrantQuantity(siteAberrantCount);

            List<CourierInfo> childDeliveryList = map.get(CourierStatusEnum.HAVE_RECEIVED.getCode());
            parentStatisticsVO.setDeliveryQuantity(CollectionUtil.isNotEmpty(childDeliveryList) ? childDeliveryList.size() : 0);


            List<CourierInfo> storageCourierInfos = courierInfos.stream()
                    //根据两个属性进行过滤
                    .collect(Collectors.toList());
            if (!TextUtils.isEmpty(statisticsQueryDTO.getStartTime()) && !TextUtils.isEmpty(statisticsQueryDTO.getEndTime())) {
                Long startTime = DateUtil.stringDate2Timespan(statisticsQueryDTO.getStartTime(), DateUtil.DATE_FORMAT_YYYY_MM_DD_HH_MM_SS);
                Long endTime = DateUtil.stringDate2Timespan(statisticsQueryDTO.getEndTime(), DateUtil.DATE_FORMAT_YYYY_MM_DD_HH_MM_SS);
                storageCourierInfos = courierInfos.stream()
                        //根据两个属性进行过滤
                        .filter(s -> s.getCreateTime().getTime() > startTime && s.getCreateTime().getTime() < endTime)
                        .collect(Collectors.toList());
            }

            parentStatisticsVO.setPendingStorageQuantity(CollectionUtil.isNotEmpty(pendingCourierInfoList) ? pendingCourierInfoList.size() : 0);
            parentStatisticsVO.setStorageQuantity(CollectionUtil.isNotEmpty(storageCourierInfos) ? storageCourierInfos.size() : 0);
            parentStatisticsVO.setTotal(courierInfos.size());
            //计算利润
            BigDecimal childTotal = new BigDecimal(String.valueOf(courierInfos.size()));
//            BigDecimal childUnit = new BigDecimal("0.1");
            BigDecimal childUnit = new BigDecimal(courierSite.getFee());
            BigDecimal childResult = childTotal.multiply(childUnit);
            totalAmount = totalAmount.add(childResult);
            parentStatisticsVO.setIncome(childResult.toString());
            parentStatisticsVOList.add(parentStatisticsVO);
        }
        pageList.setRecords(parentStatisticsVOList);
        queryStatisticsVO.setIncome(totalAmount.toString());
        queryStatisticsVO.setList(pageList);

        return queryStatisticsVO;
    }


    private List getExcelParentQueryStatisticsVO(StatisticsQueryDTO statisticsQueryDTO) {
        List<CourierSite> courierSiteList = courierSiteService.list();

        Map<Integer, String> map = courierSiteList.stream().collect(Collectors.toMap(CourierSite::getId, CourierSite::getSiteName, (key1, key2) -> key2));

        LambdaQueryWrapper<CourierInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .gt(StringUtils.isNotBlank(statisticsQueryDTO.getStartTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getStartTime())
                .lt(StringUtils.isNotBlank(statisticsQueryDTO.getEndTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getEndTime())
                .eq(CourierInfo::getSiteId, statisticsQueryDTO.getSiteId())
                .eq(Objects.nonNull(statisticsQueryDTO.getCourierStatus()), CourierInfo::getCourierStatus, statisticsQueryDTO.getCourierStatus())
                .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());

        List<CourierInfo> pageList = list(queryWrapper);

        if (CollectionUtil.isEmpty(pageList)) {
            return pageList;
        }

        Map<Integer, List<CourierInfo>> siteMap = pageList.stream()
                .collect(Collectors.groupingBy(CourierInfo::getNextSiteId));


        List<ParentStatisticsVO> parentStatisticsVOList = Lists.newArrayList();
        Set<Integer> set = siteMap.keySet();
        for (Integer siteId : set) {


            LambdaQueryWrapper<CourierInfo> pendingWrapper = new LambdaQueryWrapper<>();
            pendingWrapper.gt(StringUtils.isNotBlank(statisticsQueryDTO.getStartTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getStartTime())
                    .lt(StringUtils.isNotBlank(statisticsQueryDTO.getEndTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getEndTime())
                    .eq(CourierInfo::getNextSiteId, siteId)
                    .eq(CourierInfo::getCourierStatus, CourierStatusEnum.STORAGE.getCode())
                    .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
            List<CourierInfo> pendingCourierInfoList = list(pendingWrapper);


            LambdaQueryWrapper<CourierInfo> courierQueryWrapper = new LambdaQueryWrapper<>();
            courierQueryWrapper.gt(StringUtils.isNotBlank(statisticsQueryDTO.getStartTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getStartTime())
                    .lt(StringUtils.isNotBlank(statisticsQueryDTO.getEndTime()), CourierInfo::getUpdateTime, statisticsQueryDTO.getEndTime())
                    .eq(CourierInfo::getSiteId, siteId)
                    .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
            List<CourierInfo> courierInfos = list(courierQueryWrapper);
            Map<Integer, List<CourierInfo>> statusMap = courierInfos.stream()
                    .collect(Collectors.groupingBy(CourierInfo::getCourierStatus));

            ParentStatisticsVO parentStatisticsVO = new ParentStatisticsVO();
            parentStatisticsVO.setSiteId(siteId);
            parentStatisticsVO.setSiteName(map.get(siteId));
            parentStatisticsVO.setPendingStorageQuantity(CollectionUtil.isNotEmpty(pendingCourierInfoList) ? pendingCourierInfoList.size() : 0);


            List<CourierInfo> returnStorages = statusMap.get(CourierStatusEnum.RETURN_STORAGE.getCode());
            List<CourierInfo> returnDeliverys = statusMap.get(CourierStatusEnum.RETURN_DELIVERY.getCode());
            int siteAberrantCount = (CollectionUtil.isNotEmpty(returnStorages) ? returnStorages.size() : 0) + (CollectionUtil.isNotEmpty(returnDeliverys) ? returnDeliverys.size() : 0);
            parentStatisticsVO.setAberrantQuantity(siteAberrantCount);
            List<CourierInfo> childDeliveryList = statusMap.get(CourierStatusEnum.DELIVERY.getCode());
            parentStatisticsVO.setDeliveryQuantity(CollectionUtil.isNotEmpty(childDeliveryList) ? childDeliveryList.size() : 0);


            Long startTime = DateUtil.stringDate2Timespan(statisticsQueryDTO.getStartTime(), DateUtil.DATE_FORMAT_YYYY_MM_DD_HH_MM_SS);
            Long endTime = DateUtil.stringDate2Timespan(statisticsQueryDTO.getEndTime(), DateUtil.DATE_FORMAT_YYYY_MM_DD_HH_MM_SS);
            List<CourierInfo> storageCourierInfos = courierInfos.stream()
                    //根据两个属性进行过滤
                    .filter(s -> s.getCreateTime().getTime() > startTime && s.getCreateTime().getTime() < endTime)
                    .collect(Collectors.toList());

            parentStatisticsVO.setStorageQuantity(CollectionUtil.isNotEmpty(storageCourierInfos) ? storageCourierInfos.size() : 0);
            parentStatisticsVO.setTotal(courierInfos.size());
            //计算利润
            BigDecimal childTotal = new BigDecimal(String.valueOf(courierInfos.size()));
//            BigDecimal childUnit = new BigDecimal("0.1");
            CourierSite courierSite = courierSiteMapper.selectById(siteId);
            BigDecimal childUnit = new BigDecimal(courierSite.getFee());
            BigDecimal childResult = childTotal.multiply(childUnit);
            parentStatisticsVO.setIncome(childResult.toString());
            parentStatisticsVOList.add(parentStatisticsVO);
        }

        return parentStatisticsVOList;
    }


    private List<List<String>> head(String count) {
        List<List<String>> list = new ArrayList<List<String>>();
        List<String> head0 = new ArrayList<String>();
        head0.add("主账号入库总数");
        List<String> head1 = new ArrayList<String>();
        head1.add(count);
        list.add(head0);
        list.add(head1);
        return list;
    }

    public TodayStatisticsVO siteStatistics(TodayStatisticsQueryDTO todayStatisticsQueryDTO) {

        TodayStatisticsVO todayStatisticsVO = new TodayStatisticsVO();
        String today = DateUtil.DateToString(new Date(), DateUtil.DATE_FORMAT_YYYY_MM_DD);

        LambdaQueryWrapper<CourierInfo> storageueryWrapper = new LambdaQueryWrapper<>();
        storageueryWrapper.eq(CourierInfo::getNextSiteId, todayStatisticsQueryDTO.getChiefSiteId())
                .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode())
                .like(CourierInfo::getUpdateTime, today)
                .eq(CourierInfo::getCourierStatus, CourierStatusEnum.STORAGE.getCode());
        //今日入库数量
        List<CourierInfo> list = list(storageueryWrapper);
        List<String> codeList = list.stream().map(CourierInfo::getCourierCode).
                collect(Collectors.toList());
        todayStatisticsVO.setStorageQuantity(list.size());
        todayStatisticsVO.setCourierCodeList(codeList);

        LambdaQueryWrapper<CourierInfo> deliveryQueryWrapper = new LambdaQueryWrapper<>();
        deliveryQueryWrapper.eq(CourierInfo::getNextSiteId, todayStatisticsQueryDTO.getChiefSiteId())
                .eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode())
                .like(CourierInfo::getUpdateTime, today)
                .eq(CourierInfo::getCourierStatus, CourierStatusEnum.DELIVERY.getCode());
        //今日出库数量
        int deliveryCount = count(deliveryQueryWrapper);
        todayStatisticsVO.setDeliveryQuantity(deliveryCount);

        return todayStatisticsVO;
    }


    /**
     * push
     *
     * @param phone
     * @param type
     * @param expressName
     * @param expressNum
     * @param marketAddress
     * @throws Exception
     */
    private void push(String phone, String type, String expressName, String expressNum, String marketAddress, String subAddress, String sitePhone) throws Exception {
        try {
            HashMap<String, String> header = new HashMap<>();
            Map<String, String> map = new HashMap<>();
            map.put("phone", phone);
            map.put("type", type);
            map.put("expressName", expressName);
            map.put("expressNum", expressNum);
            map.put("marketAddress", marketAddress);
            map.put("subAddress", subAddress);
            map.put("sitePhone", sitePhone);
            log.info("push 请求参数:{}", JsonUtils.toJson(map));
            HttpResponse httpResponse = HttpUtils.doGet(configProperties.getUrl(), "/ShenBian_Web/sendExpressPush.do", null, header, map);
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity, "UTF-8");
                JSONObject jsonObject = JSONObject.parseObject(result);
                if (!"200".equals(jsonObject.get("code"))) {
                    throw new BusinessException("push 成功");
                } else {
                    log.info("push 成功");
                }
            }
        } catch (Exception e) {
            log.info("push 失败:{}", e);
            throw new BusinessException("push 失败");
        }
    }

    @Override
    public List<HiddenPhoneVO> hiddenPhoneList(HiddenPhoneQueryDTO hiddenPhoneQueryDTO) throws Exception {
        String phone = hiddenPhoneQueryDTO.getUserPhone();
        if (TextUtils.isEmpty(phone)) {
            throw new BusinessException("手机号不能为空！");
        }
//        String b = phone.replace("*", "");
//        String re = "";
//        for (int i = 0; i < 11- b.length(); i++) {
//            re += "*";
//        }
        String phoneNew = phone.replace("*", "[0-9]");
        hiddenPhoneQueryDTO.setUserPhone(phoneNew);
        hiddenPhoneQueryDTO.setSiteId(hiddenPhoneQueryDTO.getNextSiteId());
        List<CourierInfoMoreDTO> list = courierInfoMapper.hiddenPhoneCourierList(hiddenPhoneQueryDTO);
        List<HiddenPhoneVO> phoneVOList = new ArrayList<>();
        if (CollectionUtil.isEmpty(list)) {
            hiddenPhoneQueryDTO.setSiteId(null);
            list = courierInfoMapper.hiddenPhoneCourierList(hiddenPhoneQueryDTO);
        }
        for (CourierInfoMoreDTO courierInfo : list) {
            HiddenPhoneVO hiddenPhoneVO = new HiddenPhoneVO();
            hiddenPhoneVO.setUserPhone(courierInfo.getUserPhone());
            hiddenPhoneVO.setSiteName(courierInfo.getSiteName());
            phoneVOList.add(hiddenPhoneVO);
        }
        return phoneVOList;
    }

}
